Symfony有着极为好用的Controller基类,能够实现不少最为常用的控制器任务。当你的控制器继承Symfony\Bundle\FrameworkBundle\Controller\Controller类时,你可以利用若干helper方法,比如redirect()、getUser()以及createNotFoundException()等等。
这些helper是如此有用,以至我们决定再追加5个全新的helper到Symfony2.6中,来推动你的生产力。
1、redirectToRoute(),允许你基于路由名字返回一个重定向,而毋须先生成一个url:
1 2 3 4 5 6 7 8 9 |
2、 addFlash(),允许创建一个flash指定类型的信息,先检查用户session是否可用
1 2 3 4 5 | // Symfony 2.6
$this->addFlash('info', 'The item was created successfully.');
// 之前的Symfony版本
$this->get('session')->getFlashBag()->add('info', 'The item was created successfully.'); |
3、 isGranted(),用来检查给定属性是否对当前验证token给予授权,它有一个可选的受支持对象参数
1 2 3 4 5 6 7 8 9 | // Symfony 2.6
if ($this->isGranted('ROLE_ADMIN')) {
// ...
}
// 之前的Symfony版本
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
// ...
} |
4、 denyAccessUnlessGranted(),若给定属性/对象未被授权给当前用户,将抛出异常
1 2 3 4 5 6 7 | // Symfony 2.6
$this->denyAccessUnlessGranted('ROLE_EDIT', $item, 'You cannot edit this item.');
// Previous Symfony versions
if (false === $this->get('security.context')->isGranted('ROLE_EDIT', $item)) {
throw $this->createAccessDeniedException('You cannot edit this item.');
} |
5、 isCsrfTokenValid(),检查给定CSRF token的有效性
1 2 3 4 5 6 7 | // Symfony 2.6
$this->isCsrfTokenValid('token_id', 'TOKEN');
// 之前的Symfony版本
use Symfony\Component\Security\Csrf\CsrfToken;
$this->get('security.csrf.token_manager')->isTokenValid(new CsrfToken('token_id', 'TOKEN')) |
4.2翻译中
