public function with() <-- cannot pass here data anymore
{
return [
'siteName' => $this->siteName(),
'singleMovie' => $this->singleMovie($movie)
];
}
public function singleMovie($movie)
{
var_dump($movie); // null
}
Any advices about correct data injection using public static functions now? Thank you in advance for any reply.
Although that article is a little outdated, you were never able to pass data via with() in the way you seem to be implying.
Sage 10 doesn’t really make use of static methods, although there’s nothing preventing you from putting a static method on a Composer and then calling it wherever you like. Based on what you seem to be trying to do I think lambdas might be a better solution:
public function with()
{
return [
'singleMovie' => $this->singleMovie()
];
}
public function singleMovie()
{
return function($movie) {
// do some logic with $movie
}
}
Then you can call $singleMovie($movie) in your template as you do in your example.
Ok, learned about the closure you need to give me another chance. From a template with no data it works fine, but when I’m trying to call $singleMovie($movie) from shortcodes.php I’m getting error: Function name must be a string, where with() function looks the same:
public function with()
{
return [
‘singleMovie’ => $this->singleMovie()
];
}
Composers provide data to blade views. I don’t know where your shortcodes.php file is, but it’s not a blade so the Composer won’t provide any data to it. If you want to process data in a shortcode, then do that in the shortcode definition. I don’t understand why you’re putting that functionality in a Composer.
I’m planning to build a reusable component for singleMovie in app/View/Components, which can be called from any place, shortcodes.php is my custom php code added in setup next to helpers.php to keep the better structure of project.
So, I can call {!! $singleMovie !!} from single-post template and it works, cause data is from global $post variable, but how to deal with custom data when I want to pass for example 2 params to $singleMovie($data1, $data2). If I’m calling directly my public static function singleMovie($data1) there in Call to undefined function singleMovie().
Composers are not a place to put functionality you want to re-use in several different contracts; They are for logic that manipulates data to pass that data to views. The use case you’re describing is so vague that I don’t know the details of what you’re trying to accomplish, which makes it difficult to give you advice.
If you have some logic that you want to use in different contexts, then create a function that takes arguments and does that logic. Then you can use that function wherever you want, whether that’s in a Composer, a shortcode, or whatever.