【问题标题】:How to inherit parent methods with annotation routing?如何通过注解路由继承父方法?
【发布时间】:2017-12-19 20:04:27
【问题描述】:

使用 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';
    }
}

但我得到 "No route found for "GET /daily_tasks/"" 。有什么问题?如何实现我的想法?不想在每个子控制器中复制带有注释的每个动作。

【问题讨论】:

    标签: php symfony routing


    【解决方案1】:

    好的,因为我只有一个例子可以继续,这看起来像你想要实现的目标:

    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 来决定孩子是什么。

    【讨论】:

      猜你喜欢
      • 2018-01-04
      • 1970-01-01
      • 2016-05-13
      • 2019-04-11
      • 2021-11-27
      • 2012-03-11
      • 2023-04-02
      • 2011-07-30
      • 1970-01-01
      相关资源
      最近更新 更多