【问题标题】:Howto map entity by paramconverter by parent class如何通过父类通过paramconverter映射实体
【发布时间】:2018-08-17 00:24:36
【问题描述】:

我有一个父类:

<?php
namespace AppBundle\Entity\Blog;

/**
 * Class Tag
 * This is the parent class for all Tags
 */
abstract class Tag
{
    /**
      @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(name="tag_name", type="string", length=255, unique=true)
     */
    protected $tagName;

    /**
     * @ORM\Column(name="slug", type="string", length=255, unique=true)
     */
    protected $slug;
    // ... getters and setters

和 2 个子类:
其他标签

<?php
namespace AppBundle\Entity\Blog;

/**
 * OtherTag 
 * @ORM\Table(name="othertag")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\Blog\OtherTagRepository")
 */
class OtherTag extends Tag

和 JobTag

namespace AppBundle\Entity\Blog;

/**
 * JobTag
 *
 * @ORM\Table(name="jobtag")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\Blog\JobTagRepository")
 */
class JobTag extends Tag

在我的控制器中,我想通过标记名或 slug 映射标记,但我无法让它工作。我不想写每个动作(比如添加用户到标签订阅或删除用户订阅)两次,所以我想,它会像这样工作:

/**
 * Add user subscription to tag.
 * @Route("/subscription/add/{tagname}", name="subscription_add_tag")
 * @ParamConverter("tag", options={"mapping":{"tagname":"tagName"}})
 */
public function addUserTagAction(Tag $tag)
{
    //TODO: some code to add user
}

但我得到了错误:

控制器 “AppBundle\Controller\Blog\TagController::addUserTagAction()”需要 为“$tag”参数提供一个值。无论是论据 是可空的,并且没有提供空值,没有默认值 已提供或因为在此之后有一个非可选参数 一个。

如何映射子实体?

【问题讨论】:

    标签: php symfony inheritance doctrine abstract-class


    【解决方案1】:

    你可以创建你的own custom ParamConverter

    namespace Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter;
    
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
    use Symfony\Component\HttpFoundation\Request;
    
    interface ParamConverterInterface
    {
        function apply(Request $request, ParamConverter $configuration);
    
        function supports(ParamConverter $configuration);
    }
    

    然后你将它声明为服务并像使用它一样使用它

    @ParamConverter("tagname", class="AcmeBundle:Tag", converter="your_service_name")

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多