0

我有节点实体。在数据库中,我只有 id 和 title 并且想要生成 URL,我的问题是

  1. 向实体添加额外的方法是一种好习惯吗?
  2. 可以在实体中编写学说查询吗?

    $parent = $this->em->getRepository('MyDemoBundle:Nodes')->findOneBy(array("parentId" => $this->getParentId()));
    
  3. $this->getRequest()->getHost()可以在使实体 symfony 依赖的实体中使用吗?

  4. 在 NodeRepository 类中编写 getURL 方法更好吗?

  5. 实体中应该有什么,存储库类中应该有什么?

    class Node 
    {
        private $id;
        private $title;
    
       public function getId() 
       {
          return $this->id;
       }
    
       public function setId($id) 
       {
          $this->id = $id;
       }
    
       public function getTitle() 
       {
          return $this->title;
       }
    
      public function setTitle($title) 
      {
          $this->title = $title;
      }
    
      public function getURL ()
      {
            if ($this->getType() == "document") {
                $url = "http://".$this->getRequest()->getHost()."/research/" . preg_replace("/[-\s]+/", "-", strtolower(preg_replace("/[^-a-z0-9\s]+/i", "", trim($this->getTitle())))) . "-" . $this->getId() . "/";
            } elseif($this->getType() == "comment") {
                $parent = $this->em->getRepository('MyDemoBundle:Nodes')->findOneBy(array("parentId" => $this->getParentId()));
                if($this->getParentType() == "document"){
                    $url = "http://".$this->getRequest()->getHost()."/research/" . preg_replace("/[-\s]+/", "-", strtolower(preg_replace("/[^-a-z0-9\s]+/i", "", trim($parent->getTitle())))) . "-" . $this->getId();
                } else {
                    $url = "http://".$this->getRequest()->getHost()."/content/" . preg_replace("/[-\s]+/", "-", strtolower(preg_replace("/[^-a-z0-9\s]+/i", "", trim($parent->getTitle())))) . "-" . $this->getParentId() ;
                }
            } else {
                $url = "http://".$this->getRequest()->getHost()."/content/" . preg_replace("/[-\s]+/", "-", strtolower(preg_replace("/[^-a-z0-9\s]+/i", "", trim($this->getTitle())))) . "-" . $this->getId() . "/";
            }
        return $url;
       }
    
    }
    
4

2 回答 2

2

这个想法很糟糕。除此之外,您无权访问实体内的请求或实体管理器。一个实体是一个 POPO(Plain old PHP object),即一个只代表数据的虚拟对象。

如果您想使用 getter 获取父级,那么您是否应该使用正确的注释/映射(OneToMany、ManyToOne、ManyToMany)来注释字段。阅读一些关于文档的内容。有了它们,您无需编写任何查询。其他查询进入存储库类。

你应该阅读一些关于symfony 中如何生成 url 的内容。您无需参考主机。URL 主要在控制器或您需要它们输出的模板中生成。

顺便提一句。如果你想要 url 的标题,你应该看看学说扩展的sluggable 行为(可通过DoctrineExtensionsBundle安装)

总而言之,您应该阅读整本书以学习基础知识!

于 2013-07-09T09:12:00.417 回答
0

您可能还需要阅读有关如何创建自定义存储库 类这是在 symfony 中添加“自定义方法”tp 实体类的正确方法

以下是文章的介绍:

在前面的部分中,您开始从控制器内部构造和使用更复杂的查询。为了隔离、重用和测试这些查询,为您的实体创建自定义存储库类是一个很好的做法。然后可以将包含查询逻辑的方法存储在此类中。

为此,请将存储库类名称添加到实体的映射定义中:

于 2017-01-22T08:10:09.290 回答