【问题标题】:How can I call commoly used functions in slim 3 framework?slim 3框架中如何调用常用函数?
【发布时间】:2016-04-26 19:58:02
【问题描述】:

我正在 Slim 3 MVC 框架中构建我的网站。我需要为控制器调用一些常用函数(例如:对于页面标题的别名,我使用了一个名为 function getAlias(){.....} 的函数。

我必须在哪里创建这些功能?如何在控制器内部调用?

【问题讨论】:

    标签: php slim slim-3


    【解决方案1】:

    有很多方法可以做到这一点。如果这些函数没有副作用,那么一种选择是拥有一个包含静态方法的实用程序类。

    另一种选择是从一个公共类扩展所有路由操作并使用它:

    // CommonAction.php
    class CommonAction
    {
        protected function getAlias() { }
    }
    
    // HomeAction.php
    class HomeAction extends CommonAction
    {
        public function __construct(/*dependencies here*/) { }
    
        public function __invoke($request, $response, $args) {
            // route action code here
            return $response;
        }
    }
    
    // index.php
    $app = new Slim\App(require('settings.php'));
    
    $container = $app->getContainer();
    $container[HomeAction::class] = function ($c) {
        return new HomeAction(/*dependencies*/);
    }
    
    $app->get('/', HomeAction::class);
    
    $app->run();
    

    如果该功能是您的领域层的一部分,则将这些类作为依赖项注入到您的路由操作中。

    【讨论】:

      猜你喜欢
      • 2015-12-14
      • 2012-10-04
      • 2016-05-17
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-29
      • 2013-04-03
      相关资源
      最近更新 更多