hi,
I have included a section as view file , which was called from different controllers. So I have to create a new function for each controller. Is there any way to call a function in the controller from view file ??
|
Dec '17 |
3 |
1311 |
1 |
hi,
I have included a section as view file , which was called from different controllers. So I have to create a new function for each controller. Is there any way to call a function in the controller from view file ??
Basically @Wojciech answered your question. It is againsts mvc :)
To keep your code DRY you have to make a function which can be reused in controllers, views etc. Just like @Julien Turbide suggested.
Here is a simple example so you can understand better:
// Services File
$di->setShared('view', function() use ($di) {
$view = new \Phalcon\Mvc\View();
...
$view->registerEngines([
'.phtml' => function($view, $di) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
$options = [
'compiledPath' => $di->getConfig()->site->path->cache . 'volt/frontend/',
'compiledExtension' => '.php',
'compileAlways' => $di->getConfig()->debug,
];
$volt->setOptions($options);
// Extended functions
$compiler->addFilter('prettyDate', function($resolvedArgs, $exprArgs){
return 'Helpers\Volt::prettyDate(' . $resolvedArgs . ')';
});
$compiler->addFilter('asPrice', function($resolvedArgs, $exprArgs){
return 'Helpers\Volt::asPriceString(' . $resolvedArgs . ')';
});
$compiler->addFunction('url', function($resolvedArgs, $exprArgs){
return 'url(' . $resolvedArgs . ')';
});
$compiler->addFunction('strpos', 'strpos');
$compiler->addFunction('json_decode', 'json_decode');
$compiler->addFunction('in_array', 'in_array');
return $volt;
}
]);
return $view;
});
Usage:
addFilter()
registers a filter, which "modifies" the value of a variable. Example usage:
{{ item.price|asPriceString }}
in my case this will transform a decimal into user friendly string.
19.99
will become 19.99 лв.
or 19.99 BGN
depending on website language version
addFunction()
registers a fnction, which can accept one or more parameters. Example usage:
{{ url(['for': 'custom-route-name']) }}
in my case this function is extending Volt url helper function because most of my projects have multiple applications and languages. My modified version for example automatically adds Language and Application to the route name to save me some time and to not make my templates ugly :)
As you noticed, Volt does not support all PHP functions. If you happen to need some php function you can add it to volt like this:
$compiler->addFunction('strpos', 'strpos');
Well to be honest you shouldn't really call any controller logic from view.
for example : I wants to call the method in the header (Header comes to all page but I am loading different controller for different pages), So I wants to call the method from the common controller . If I am not, I have to call the method in every controller in viewAction.