-
Notifications
You must be signed in to change notification settings - Fork 122
Injecting logic before the view (composer)
It is possible to inject a logic just before the view is called or executed.
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.
We could send the user defining it explicitly.
$blade=new BladeOne();
echo $blade->run('pages.example',['user'=>'some user']);
$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.
$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)
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');
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');
The goal of the method composer() is to avoid forgetting to sets variables and we could sets for more than one page.
- Composer allows defining more than one page at the same time.
$blade->composer(['pages.example','pages.example2'],'namespace\SomeClass');
- Composer allows using wildcards (*)
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');
Copyright Jorge Castro Castillo
- BladeOne Manual
- Template tags (views)
- Custom control
- Methods of the class
- Injecting logic before the view (composer)
- Extending the class
- Using BladeOne with YAF Yet Another Framework
- Differences between Blade and BladeOne
- Comparision with Twig (May-2020)
- Changelog
- Changes between 2.x and 3.0 and TODO
- Code Protection (Sourceguardian and similars)