一直以來使用其他框架如TP何CI都做過如題的需求,也輕鬆就可以實現。最近也想在SF2上實現出來,寫一個adminBundle自動化創建後台提供常用功能。不過遇上了問題如下:
由於要全域後台檢測使用者存取的權限,我便監聽了controller .在每個controller觸發之前獲取request 的信息,檢測該使用者是否給予了相應權限。程式碼如下:
class RunActListener {
protected $securityContext;
public function __construct(SecurityContextInterface $securityContext)
$this->securityContext = $securityContext;
}
public function onRunAct(FilterControllerEvent $event) {
$request = $event->getRequest();
$ajax = $request->isXmlHttpRequest();
if (preg_match('/^\/admin/', $request->getRequestUri())) {
$routeName = $request->get('_route');
if ($this->securityContext->isGranted(array($routeName))) {
} else {
$reffeer = $request->server->get('HTTP_REFERER');
$data['info'] = '您没有权限操作!';
$data['status'] = false;
if ($ajax) {
$event->setController(
function() use ($data) {
return new JsonResponse($data);
});
} else {
$event->setController(
function() use ($data) {
return new Response('<b>您没有足够的访问权限!</b><script>setTimeout("window.history.back(-1)",2000)</script>');
});
//。。。。。
然後我在後台layout都引入了2個render ,選單和麵包屑程式碼如下:
<nav id="navigation" class="collapse">
<ul>
{{ render(controller( 'CwpUtilBundle:Menu:showMenu')) }}
</ul>
</nav>
</aside>
<p id="sidebar-separator"></p>
<section id="main" class="clearfix">
<p id="main-header" class="page-header">
{{ render(controller( 'CwpUtilBundle:Menu:showCrumb')) }}
</p>
<p id="main-content">
{% block main %}
{% endblock %}
</p>
</section>
這樣了發起了2個sub_request ,但我的需求要在sub_request 裡取得parent request的url 來實現我的麵包屑和選單。在SF當中有些麻煩,有大神建議用get request stack 在sub action 中
/**
* 显示面包屑
* @return type
*/
public function showCrumbAction() {
$request = $this->container->get('request');
$path = $request->server->get('REDIRECT_URL');
$path_arr = explode('/', $path);
$path_len = count($path_arr);
$top_index = (int) ($path_len - 2);
$path_top = $path_arr[$top_index];
$route_arr = $this->get('router')->match($path);
$route = $route_arr['_route'];
$em = $this->getDoctrine()->getManager();
//获取菜单结果集
$top_menu = $em->getRepository('CwpUtilBundle:Menu')->findOneByNode($path_top);
$sec_menu = $em->getRepository('CwpUtilBundle:Menu')->findOneByNode($route);
return $this->render('CwpUtilBundle:Layout:crumb.html.twig', array(
'top_menu' => $top_menu,
'sec_menu' => $sec_menu,
));
}
我嘗試在以上action get request_stack ,但是一旦我get,似乎就在這個action 發起了request ,我的listener就被觸發,然後執行了else ,跳到提示 你的權限不足。我表示很茫然,不知道什麼原因。
監聽kernel.controller的那個listener,加個判斷,僅在主請求時才檢查權限就可以了:
2.3的FilterControllerEvent沒這個方法,參考這個邏輯自己寫就可以了:
https://github.com/symfony/symfony/blob/2.7/src/Symfony/Component/HttpKernel/Event/KernelEvent.php#L100