2017-07-14 65 views
1

使用Symfony 3.4。要保持在抽象父类中的所有功能,并且只需设置路由前缀在孩子的:如何使用注释路由继承父级方法?

namespace AppBundle\Controller; 

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 

abstract class TaskAbstractController extends Controller 
{ 

    /** 
    * Lists all Task entities. 
    * 
    * @Route("/", name="tasks_index") 
    * @Method("GET") 
    */ 
    public function indexAction() 
    { 
     $em = $this->getDoctrine()->getManager(); 

     $tasks = $em->getRepository($this->getTargetClassName())->findAll(); 
     return $this->render('@App/' . $this->getPrefix() . '/index.html.twig', array(
      'tasks' => $tasks, 
      'delete_forms' => $this->generateDeleteFormsViews($tasks) 
     )); 
    } 

孩子:

/** 
* Daily task controller. 
* 
* @Route("daily_tasks") 
*/ 
class DailyTaskController extends TaskAbstractController 
{ 

    protected function getPrefix(): string 
    { 
     return 'daily_task'; 
    } 

    protected function getTargetClassName(): string 
    { 
     return 'AppBundle:DailyTask'; 
    } 
} 

,但我得到“未找到路线‘GET/daily_tasks /’” 。有什么问题?如何实现我的想法?不想在每个子控制器中复制每个带有注释的操作。

回答

1

OK,因为我只有这一个例子去,这看起来像什么你要实现的目标:

class TaskAbstractController extends Controller 
{ 
    /** 
    * Lists all Task entities. 
    * 
    * @Route("/{prefix}", name="tasks_index", requirements={"prefix":"daily_task|add_some_more"}) 
    * @Method("GET") 
    */ 
    public function indexAction($prefix) 
    { 
     $em = $this->getDoctrine()->getManager(); 

     /** @var TaskFactory $taskFactory */ 
     $taskFactory = $this->container->get('task_factory'); 
     $task  = $taskFactory->get($prefix); 

     $tasks = $em->getRepository($task->getTargetClassName())->findAll(); 

     return $this->render('@App/'.$prefix.'/index.html.twig', 
      [ 
       'tasks'  => $tasks, 
       'delete_forms' => $this->generateDeleteFormsViews($tasks), 
      ]); 
    } 
} 

class TaskFactory 
{ 
    public function get(string $prefix): TaskInterface 
    { 
     $map = [ 
      'daily_task' => DailyTask::class, 
     ]; 

     if (isset($map[$prefix])) { 
      return new $map[$prefix]; 
     } 

     throw new \RuntimeException('task not found'); 
    } 
} 

interface TaskInterface 
{ 
    public function getTargetClassName(): string; 
} 

动态让路线,并确定所有可能的值的要求。无论如何,你必须在@Route()方法中做类似的事情。

TaskFactory然后根据$prefix决定孩子是什么。

+0

它确实有效!谢谢你花时间。 – Audiophile