soluti/mongo-bundle

一个提供连接到MongoDB的扩展包

v0.1.0 2017-09-04 08:31 UTC

This package is not auto-updated.

Last update: 2021-10-15 21:52:01 UTC


README

提供了一种使用MongoDB新PHP驱动的方法。

安装

在你的composer.json中要求安装soluti/mongo-bundle包并更新你的依赖。

$ composer require soluti/mongo-bundle

将SolutiMongoBundle添加到你的应用程序kernel中

    public function registerBundles()
    {
        $bundles = array(
            // ...
            new Soluti\MongoBundle\SolutiMongoBundle(),
            // ...
        );
        // ...
    }

配置

要启用在MongoDB中存储会话,请向config.yml添加以下内容

framework:
    session:
        storage_id: app.mongo.session_storage
        cookie_httponly: true
        cookie_secure: true

使用方法

你可以使用以下两种类型的模型:

  • 保存在它们自己的集合中
  • 作为另一个模型的组成部分嵌入

要创建一个保存在其自己的集合中的模型,需要以下内容:

  • 一个模型
  • 一个仓库
  • 一个填充器
模型

为了创建可以持久化的模型,你的模型应该实现Soluti\MongoBundle\Model\ReferenceInterface。一个良好的起点是扩展Soluti\MongoBundle\Model\BaseModel

重要!!!如果基字段类型有getter/setter,则会映射所有基础字段类型。更复杂类型应通过注入填充器进行映射。

namespace AppBundle\Model;

use Soluti\MongoBundle\Model\BaseModel;
use Soluti\MongoBundle\Model\Core\Geo;
use Soluti\MongoBundle\Model\ReferenceInterface;

class User extends BaseModel implements ReferenceInterface
{
    ...
    /** @var Geo */
    protected $geo;
    
    /**
     * @return Geo
     */
    public function getGeo(): Geo
    {
        return $this->geo;
    }

    /**
     * @param Geo $geo
     */
    public function setGeo(Geo $geo)
    {
        $this->geo = $geo;
    }
    ...
}
仓库

你的仓库应该扩展Soluti\MongoBundle\Repository\BaseRepository并实现缺失的方法。这样一个仓库的示例:

namespace AppBundle\Repository;

use AppBundle\Model\User;
use Soluti\DataFilterBundle\Repository\MongoRepository;

class DeviceRepository extends MongoRepository
{
    /**
     * @inheritdoc
     */
    public static function getCollectionName()
    {
        return User::getCollectionName();
    }

    /**
     * @inheritdoc
     */
    public static function getClassName()
    {
        return User::class;
    }
}

填充器

填充器应该实现Soluti\MongoBundle\Hydrator\HydratorInterface,该包提供了一个Soluti\MongoBundle\Hydrator\BaseHydrator用于快速使用。你可以通过DI注入任何其他填充器,并只需提供一个简单的配置以将它们适当地链接起来。

namespace AppBundle\Hydrator;

use AppBundle\Model\Device;
use Soluti\MongoBundle\Hydrator\BaseHydrator;
use Soluti\MongoBundle\Hydrator\HydratorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class UserHydrator extends BaseHydrator implements HydratorInterface
{
    const OBJECT = User::class;

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->config = [
            'geo' => ['hydrator' => $container->get('soluti_mongo.hydrator.geo')],
            'geoUpdatedAt' => ['hydrator' => $container->get('soluti_mongo.hydrator.datetime')],
            'createdAt' => ['hydrator' => $container->get('soluti_mongo.hydrator.datetime')],
        ];
    }
}