Question

I am using phalcon php framework for my application. This application is verry interactive using javascript verry often.

Is there an class / service that also wil include the js controller according to there name, else if it's not found include the 'main' javascript file?

For example I am requesting the url: http://www.mysite.com/search/keyword

So phalcon will execute the searchController with the indexAction including the parameter. The data returned from the indexAction function will be passed to the views.

The view will also include js/search/index.js

(maybe additionally including a css file css/search/index.css!?)

Is there a function for this type of hierarchy functionality for js?

Was it helpful?

Solution

There's nothing out of the box, but this is relatively easy to achieve. You can implement that logic in the base controller, something along those lines:

abstract class AbstractController extends \Phalcon\Mvc\Controller
{
    public function afterExecuteRoute()
    {

        // Don't want to add assets if the action gets forwarded.

        if (!$this->dispatcher->isFinished()) {
            return;
        }

        $controllerName = $this->dispatcher->getControllerName();
        $actionName = $this->dispatcher->getActionName();
        $path = 'js/' . $controllerName. '/' . $actionName . '.js';

        // Defining APPLICATION_PATH global constant is one way of pointing to the root of your application. 
        // This can be done in your config or index. Alternatively you could add config to your DI and do 
        // something like DI::getDefault()->getShared('config')->applicationPath.

        if (file_exists(APPLICATION_PATH . '/public/' . $path)) {
            $this->assets->addJs($path);
        } else {
            $this->assets->addJs('js/main.js');
        }
    }
}

And in the view output them as usual:

<html>
    <head>
        <title>Some amazing website</title>
        <?php $this->assets->outputCss() ?>
    </head>
    <body>

        <!-- ... -->

        <?php $this->assets->outputJs() ?>
    </body>
<html>

Have a look at controller events, they come in really handy at times like this.

Updated

Another possible approach is to tight up the selection of js with the view selection logic. The view will check for views/controller/action.volt, views/layouts/controller.volt, etc., read more about hierarchical rendering. This will help to keep things neater by matching the js hierarchy with the actual view hierarchy. It's up to you how you implement this, but it would probably be best to keep it all in the same afterExecuteRoute handler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top