symfony 中将数据库操作 Repository 封装成 service

最近了解到了sylius这个框架,发现这个框架将symfony运用的真是特别牛逼。

于是,学习了一下他的代码。发现真的很厉害。各种程度都写的特别完美。

于是今天偷师了一种工厂模式、

工厂模式:

在symfony中,我们又各种各样的工厂。比如doctrine的工厂。

为了让这个doctrine对象能成为一个服务,我们需要配置服务容器。以便能够使用doctrine中的所有可用的方法。

我们可以在service.yml中这样记录

    ahn_admin_orders:
        class: ahn_admin_orders
        factory: 'doctrine.orm.entity_manager:getRepository'

这样的话,就可以了。

我们可以传递一些参数给他。

parameters:
   ahn_admin_order_class: Ahn\Component\Entity\Orders

services:
    ahn_admin_orders:
        class: ahn_admin_orders
        factory: 'doctrine.orm.entity_manager:getRepository'
        arguments:
            class: "%ahn_admin_order_class%"

然后我个人喜欢把Entity以及Repository数据放在一个单独的文件内,

就像下面这样

symfony中将数据库操作Repository封装成service

然后我在任意一个bundle中建立一个service.yml文件

来放置我所有的数据库操作。

parameters:
   ahn_admin_order_class: Ahn\Component\Entity\Orders

services:
    ahn_admin_orders:
        class: ahn_admin_orders
        factory: 'doctrine.orm.entity_manager:getRepository'
        arguments:
            class: "%ahn_admin_order_class%"

然后要调用的话就直接以获取服务的方式来获取


 public function indexAction()
    {
        $test = $this->getDoctrine()->getManager();
        $test1 = $this->get('ahn_admin_orders')->test(1);
        dump($test1);exit;
        return $this->render('AhnAdminBundle:Default:index.html.twig');
    }

于是这样我们以后来操作数据库就更加强了。

讨论数量: 2

你路由不写注释么

4年前 评论
coffey (楼主) 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!