Skip to content

Injecting logic before the view (composer)

Jorge Castro edited this page Jun 6, 2020 · 3 revisions

It is possible to inject a logic just before the view is called or executed.

Example code

https://github.com/EFTEC/BladeOne/blob/master/examples/example_composer.php

Definition

For example, let's say the next view (pages/example.blade.php)

<div>Current user is {{$user}}</div>
<h1>Our page...</h1>

It needs to show the user each time it is called.

Normal method

We could send the user defining it explicitly.

$blade=new BladeOne();
echo $blade->run('pages.example',['user'=>'some user']);

Normal method using a fluent expression.

$blade=new BladeOne();
echo $blade->setView('pages.example') // it sets the view to render
         ->shared(['user'=>'some user']) // it sets the variable or variables.
         ->run(); // and it executes and renders the view.

Composer using a function

$blade=new BladeOne();
$blade->composer('pages.example',function($view) {
   $view->share('user','some user');  // it adds the variable to the view. ($view is an instance of BladeOne)
});
echo $blade->run('pages.example');

Note: For performance, It is recommended to call the function statically, i.e. static function($view) instead of function($view)

Composer using an instance.

It requires the class has defined a method called composer()

class SomeClass {
    function composer($view) { // ($view is an instance of BladeOne)
          $view->share('user','some user');
    }
}
$obj=new SomeClass();

$blade=new BladeOne();
$blade->composer('pages.example',$obj);
echo $blade->run('pages.example');

Composer using a class

It tries to call the method called composer, first statically. If it is not able to call it statically, then it creates an instance to call the method.

class SomeClass {
    function composer($view) {
          $view->share('user','some user');
    }
}
$obj=new SomeClass();

$blade=new BladeOne();
$blade->composer('pages.example','namespace\SomeClass');
echo $blade->run('pages.example');

But what is the functionality of composer() anyways 🤷‍♀️?

tl/dr: if you need to send common values to many views, then this functionality is for you.

The goal of the method composer() is to avoid forgetting to sends variables to the view, so we could define it implicitly and for many pages at once.

    1. Composer allows defining more than one page at the same time.
$blade->composer(['pages.example','pages.example2'],'namespace\SomeClass');
    1. Composer allows using wildcards (*) to sets a functionality for more than one page at once.

The wildcard symbol only could be defined at the start, end, or both.

$blade->composer('pages.*','namespace\SomeClass');
$blade->composer('*.customers','namespace\SomeClass');
$blade->composer('*.folder.*','namespace\SomeClass');
Clone this wiki locally