I’m new to CakePHP but I’m enjoying it so far. However, I’m still getting used to the conventions used by it.
One of the things I don’t understand is that in the basic example that ships with CakePHP, we get a router passing the controller name, the action and also an additional parameter, which would be the template name/path to the template, however, inside that controler, we have a long code, like this:
public function display(...$path)
{
if (!$path) {
return $this->redirect('/');
}
if (in_array('..', $path, true) || in_array('.', $path, true)) {
throw new ForbiddenException();
}
$page = $subpage = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
$this->set(compact('page', 'subpage'));
try {
$this->render(implode('/', $path));
} catch (MissingTemplateException $exception) {
if (Configure::read('debug')) {
throw $exception;
}
throw new NotFoundException();
}
}
I understand that it’s just an example that we actually could handle the path and throw customized errors, but I would like to know if there’s any way to pass the view as parameter and have them set automatically, or we could just do this:
$this->render('template-name');
Like let’s say my template is called page.ctp
or page.php
and I want to pass variables to this template from a controller, I would just do:
$this->set('variable', "I'm a variable");
$this->render('page');
But what If I want to send this variable to my page
template without using the render
function? Is there any way to do it using just the route like in the example?
Like let’s say the page template is the index:
$routes->connect('/', ['controller' => 'ShowVariable', 'action' => 'displayVar', 'page']);
function displayVar(){
$this->set('variable', "I'm a variable");
}
and I display it in my page template like this:
<?=$variable?>
Would I still have to use $this->render('page');
? If so, is this additional parameter in the route any useful?
Another question I would like to ask is, since we can access controllers via URL, routes become less important, right?