我目前正在学习Slim Framework v4,以创建一个基于mysql的配置文件网站。
[我有一个导航栏,正在使用twig系统检查用户是否已登录以显示帐户用户名或其他登录/注册按钮,但目前我必须将用户类传递给每个路由,才能正常工作。
routes.php
// Home
$app->any('/', 'App\Controllers\HomeController:index')->setName('index');
$app->get('/profile', 'App\Controllers\ProfileController:index')->setName('profile.index');
$app->any('/profile/settings', 'App\Controllers\ProfileController:settings')->setName('profile.settings');
HomeController.php
class HomeController extends BaseController
{
protected $model = Tournaments::class;
public function indexAction()
{
$user = User::userData();
return $this->render('index', [
'user' => $user
]);
}
}
navbar.php
{% if user.isLoggedIn() == false %}
<a class="btn btn-outline-light" style="margin-left: 10px;" href="/login">Login</a>
<a class="btn btn-outline-light" style="margin-left: 10px;" href="/register">Register</a>
{% else %}
<a class="nav-item" href="/profile">{{ user.username }}</a>
{% endif %}
我浏览了苗条的文档,并认为可以通过使用中间件来解决这个问题,但我无法实现。因此,任何解释将不胜感激!
我试图渲染到每个页面的类函数是$ user = User :: userData();如您在HomeController.php中看到的]
我正在使用细长的v4框架,并且已经具有内置的应用程序中间件。
使用对象时,以后可以更改全局变量的值。仍然无法替换对象本身,但是之后可以更改对象的属性值。
注册全局树枝变量:
$environment = $twig->getEnvironment();
$environment->addGlobal('user', (object)[
'id' => null,
]);
更改中间件的值:
$user = $this->twig->getEnvironment()->getGlobals()['user'];
// Set the new value
$user->id = 1234
在树枝上:
{{ user.id }}
输出:1234
除了全局变量,您还可以引用服务容器中的服务。要延迟加载服务,只需将调用包装到Twig函数中即可:
$environment->addFunction(new \Twig\TwigFunction('user', function () use ($container) {
// Return the values...
return User::userData();
// or fetch the service object from the container
//return $container->get(UserAuth::class);
}));
在树枝上:
{{ user.id }}
或使用服务方法时:
{{ user().getUser().id }}