我如何在瘦框架中定义全局变量


How can i define global variables in slim framework

我如何定义一个全局变量,这样我的current_user方法可以工作,我想要它,所有我简单需要做的是检查是否有一个当前用户我的示例代码在

    if (isset($_SESSION['company_id'])) {
       $current_user = Companies::find($_SESSION['company_id']);
     }
    else
   {
    $current_company = null;
   }

我如何使用当前的用户方法在任何地方,我想没有传递它到我的app->render()方法就像在我的标题。html

{% if current_user %}
 hi {{current_user.name}}
{% endif %}

你可以在app对象中注入一个值:

$app->foo = 'bar';

更多关于Slim的文档

注入在回调函数中不起作用。

要访问回调函数中的变量,可以使用"use() "函数:

$mydata =  array (  ... );
$app->get('/api', function(Request $request, Response $response) use($mydata) {  
        echo json_encode($mydata);
});

像这样注入对象:

$app->companies = new Companies();

如果你想确保每次都是同一个,你也可以把它作为单例注入:

$app->container->singleton('companies', function (){
    return new Companies();
});

可以这样调用:

$app->companies->find($_SESSION['company_id']);

UPDATE DOC LINK:精简依赖注入

接受的答案不适用于Slim 3(因为钩子已被移除)。

如果你试图为所有视图定义一个变量,并且你正在使用PhpRenderer,你可以效仿他们的例子:

// via the constructor
$templateVariables = [
    "title" => "Title"
];
$phpView = new PhpRenderer("./path/to/templates", $templateVariables);
// or setter
$phpView->setAttributes($templateVariables);
// or individually
$phpView->addAttribute($key, $value);

我终于可以让它工作了

   $app->hook('slim.before.dispatch', function() use ($app) { 
       $current_company = null;
       if (isset($_SESSION['company_id'])) {
          $current_company = Company::find($_SESSION['company_id']);
       }
       $app->view()->setData('current_company', $current_company);
    });

With twig/view

创建中间件

<?php
namespace ETA'Middleware;
class GlobalVariableMiddleware extends Middleware {
    public function __invoke($request, $response, $next) {
        $current_path = $request->getUri()->getPath();
        $this->container->view->getEnvironment()->addGlobal('current_path', $current_path);
        return $next($request, $response);
    }
}