How to define global variables in slim framework

How can I define a global variable so that my current_user method can work, someday I want it, all I just need to do is check if there is a current user, my sample code below

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

how can I use the current user method when I want, without passing it to the method app->render(), as in my header.html

{% if current_user %}
 hi {{current_user.name}}
{% endif %}
+4
source share
6 answers

i finally was able to get him to work with this

   $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);
    });
0
source

You can enter a value in the application object:

$app->foo = 'bar';

Read more about Slims Documentation .

+6
source

.

, "use() ":

$mydata =  array (  ... );

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

});
+3

:

$app->companies = new Companies();

You can also enter it as a single if you want to make sure that it is the same every time:

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

Call it like this:

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

UPDATE DOC LINK: Slim Dependency Injection

+2
source

The accepted answer does not work for Slim 3 (since the hooks have been removed).

If you are trying to define a variable for all views and are using PhpRenderer , you can follow their example:

// via the constructor
$templateVariables = [
    "title" => "Title"
];
$phpView = new PhpRenderer("./path/to/templates", $templateVariables);

// or setter
$phpView->setAttributes($templateVariables);

// or individually
$phpView->addAttribute($key, $value);
+1
source

With a twig / view

creating middleware

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

}
0
source

Source: https://habr.com/ru/post/1540459/


All Articles