【问题标题】:phalcon php include js according to there controller and action namephalcon php 根据那里的控制器和动作名称包含 js
【发布时间】:2014-06-04 23:20:44
【问题描述】:

我正在为我的应用程序使用 phalcon php 框架。 此应用程序非常频繁地使用 javascript 进行交互。

是否有一个类/服务也将根据那里的名称包含 js 控制器,否则如果未找到包含“主”javascript 文件?

例如,我正在请求 url: http://www.mysite.com/search/keyword

因此 phalcon 将使用包含参数的 indexAction 执行 searchController。 indexAction 函数返回的数据将被传递给视图。

视图还将包括 js/search/index.js

(可能还包括一个css文件css/search/index.css!?)

这种类型的js层级功能有函数吗?

【问题讨论】:

    标签: javascript php phalcon


    【解决方案1】:

    没有什么是开箱即用的,但这相对容易实现。您可以在基本控制器中实现该逻辑,类似于以下内容:

    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');
            }
        }
    }
    

    在视图中output them as usual

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

    看看controller events,他们在这种时候真的很方便。

    更新

    另一种可能的方法是使用视图选择逻辑来加强对 js 的选择。该视图将检查views/controller/action.voltviews/layouts/controller.volt 等,了解更多关于hierarchical rendering 的信息。通过将 js 层次结构与实际的视图层次结构相匹配,这将有助于保持整洁。这取决于您如何实现它,但最好将其全部保存在同一个 afterExecuteRoute 处理程序中。

    【讨论】:

    • 谢谢!如果文件存在并且包含“主”js文件,我如何检查phalcon框架?
    • 这完全取决于您。幸运的是,Phalcon 并没有为每种情况提供“标准”解决方案,因此常规的 php 在这里完全可以使用。我已经更新了答案给你一些想法。
    猜你喜欢
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2013-08-17
    • 2015-01-13
    • 1970-01-01
    • 2017-12-08
    相关资源
    最近更新 更多