Php 如何通过注释路由继承父方法?
使用Symfony 3.4。要在父抽象类中保留所有功能,只需在childs中设置路由前缀:Php 如何通过注释路由继承父方法?,php,symfony,routing,Php,Symfony,Routing,使用Symfony 3.4。要在父抽象类中保留所有功能,只需在childs中设置路由前缀: namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; abstract class TaskAbstractController extends Controller { /** * Lists all Task entities. *
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/”的路由。有什么问题吗?如何实现我的想法?我不想在每个子控制器中复制带有注释的每个操作。好的,因为我只有一个例子要讲,这看起来像是您试图实现的:
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
决定子级是什么