这是我的环境:
我有一个实体:
Object
|____ id (integer)
|____ foo (string)
|____ configurations (collection)
Run Code Online (Sandbox Code Playgroud)
该属性configurations是使用a Configuration映射的实体的集合oneToMany.无论如何,这看起来像这样:
Configuration
|____ id (integer)
|____ bar (string)
|____ name (string, nullable)
Run Code Online (Sandbox Code Playgroud)
我有一个服务来获得一个object:
该服务是一个管理许多项目对象的包.
此服务不知道哪个项目调用它.
此服务是一组过滤器,事件侦听器和SQL查询.(约2K行)
考虑一下我不能/不想更新它的get过程,我想在这里做什么.
我有一个我想在我的控制器中执行的操作,如下所示:
$objMgr = $this->get('objectManager'); //get my service I talked before
$object = $objMgr->findOneById(); //get my object
return array('object' => $object);// render template
Run Code Online (Sandbox Code Playgroud)
我有很多主题管理最终用户屏幕,每个主题都有一个twig文件:
theme1
|____ object_details.html.twig
theme2
|____ object_details.html.twig
themeX
|____ object_details.html.twig
Run Code Online (Sandbox Code Playgroud)
这些object_details.html.twig代码用于打印配置.
{% for config in object.configurations %}
{# div config.blablabla etc. #}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
根据上面的上下文,我可以排除name属性不为null的所有配置吗?
答案不会编辑树枝文件(我知道怎么做^^)
我想确保排除a configuration,不会被doctrine检测到,并且它会config在代码中的某个随机刷新中删除我的数据库.
答案可能是:"老兄,我们做不到".事实上,我很想知道它是否可能.我现在不知道.
答案必须尊重一些最佳实践:)
评论期待:为什么不编辑twig文件?:我有很多主题,我想知道是否可以做一次.
为什么不在数据库查询中排除结果?:因为我希望使用此getter在我的其他页面和项目中进行这些配置.
+50为最好的尝试:)
基于我上面的评论:
一种选择是实现一个(可配置的)装饰器,它公开与原始对象相同的 api,除了视图之外不会反映任何内容。
这样,视图甚至其他消费者甚至不会知道他们正在处理特殊情况。
例如:
<?php
namespace App\Something;
use Doctrine\Common\Collections\Criteria;
class ObjectDecorator /* implement ObjectInterface // if needed */
{
public function __construct(Object $object)
{
$this->base = $object;
}
public function getConfigurations()
{
//Using Criteria to make it cleaner than a loop.
$criteria = Criteria::create();
$criteria->where(Criteria::expr()->isNull('name'));
return $this->base->getConfigurations()->matching($criteria);
}
/*
Override all your decorated entity getters with
public function getFoo()
{
return $this->base->getFoo();
}
*/
}
Run Code Online (Sandbox Code Playgroud)
并在您的控制器中使用:
return array('object' => new ObjectDecorator($object));
Run Code Online (Sandbox Code Playgroud)
您可以通过多种方式扩展它:
| 归档时间: |
|
| 查看次数: |
181 次 |
| 最近记录: |