nick4fake / doctrine-behaviors
Doctrine2行为特性
Requires
- php: >=5.4.0
- doctrine/common: >=2.2
Requires (Dev)
- ext-pdo_pgsql: *
- ext-pdo_sqlite: *
- doctrine/mongodb-odm: dev-master
- doctrine/orm: >=2.2
- phpunit/phpunit: ~3.7
This package is not auto-updated.
Last update: 2022-02-01 12:43:24 UTC
README
这是一个php 5.4+库,它收集了一系列特性,可以添加到Doctrine2实体和仓库中。
目前它处理以下特性
注意
某些行为(可翻译、时间戳、软删除、责任归属、地理位置可编码)需要Doctrine订阅者才能工作。确保通过阅读订阅者部分来激活它们。
订阅者
如果你使用symfony2,你可以通过导入服务定义文件轻松注册它们
# app/config/config.yml imports: - { resource: ../../vendor/knplabs/doctrine-behaviors/config/orm-services.yml }
你也可以使用doctrine2 API来注册它们
<?php $em->getEventManager()->addEventSubscriber(new \Knp\DoctrineBehaviors\ORM\Translatable\TranslatableSubscriber); // register more if needed
使用方法
你所要做的就是定义一个Doctrine2实体并使用特性
<?php use Doctrine\ORM\Mapping as ORM; use Knp\DoctrineBehaviors\Model as ORMBehaviors; /** * @ORM\Entity(repositoryClass="CategoryRepository") */ class Category implements ORMBehaviors\Tree\NodeInterface, \ArrayAccess { use ORMBehaviors\Tree\Node, ORMBehaviors\Translatable\Translatable, ORMBehaviors\Timestampable\Timestampable, ORMBehaviors\SoftDeletable\SoftDeletable, ORMBehaviors\Blameable\Blameable, ORMBehaviors\Geocodable\Geocodable, ORMBehaviors\Loggable\Loggable, ORMBehaviors\Sluggable\Sluggable ; /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="NONE") */ protected $id; }
对于一些行为,如树状结构,你可以使用仓库特性
<?php use Doctrine\ORM\EntityRepository; use Knp\DoctrineBehaviors\ORM as ORMBehaviors; class CategoryRepository extends EntityRepository { use ORMBehaviors\Tree\Tree, }
就是这样!
现在你有一个工作的Category
,它表现得像
树状结构
<?php $category = new Category; $category->setId(1); // tree nodes need an id to construct path. $child = new Category; $child->setId(2); $child->setChildOf($category); $em->persist($child); $em->persist($category); $em->flush(); $root = $em->getRepository('Category')->getTree(); $root->getParent(); // null $root->getChildNodes(); // ArrayCollection $root[0][1]; // node or null $root->isLeaf(); // boolean $root->isRoot(); // boolean
可翻译
如果你正在处理Category
实体,则Translatable
行为期望一个CategoryTranslation
实体。这种命名约定可以避免你手动处理实体关联。它由TranslationSubscriber自动处理。
为了使用Translatable特性,你必须创建这个CategoryTranslation
实体。
<?php use Doctrine\ORM\Mapping as ORM; use Knp\DoctrineBehaviors\Model as ORMBehaviors; /** * @ORM\Entity */ class CategoryTranslation { use ORMBehaviors\Translatable\Translation; /** * @ORM\Column(type="string", length=255) */ protected $name; /** * @ORM\Column(type="string", length=255) */ protected $description; /** * @return string */ public function getName() { return $this->name; } /** * @param string * @return null */ public function setName($name) { $this->name = $name; } /** * @return string */ public function getDescription() { return $this->description; } /** * @param string * @return null */ public function setDescription($description) { $this->description = $description; } }
相应的Category实体需要使用use ORMBehaviors\Translatable\Translatable;
并且只应包含不需要翻译的字段。
<?php
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
/**
* @ORM\Entity
*/
class Category
{
use ORMBehaviors\Translatable\Translatable;
/**
* @ORM\Column(type="string", length=255)
*/
protected $someFieldYouDoNotNeedToTranslate;
}
在更新数据库后,即使用./console doctrine:schema:update --force
,你现在可以使用translate
或getTranslations
方法进行翻译工作。
<?php $category = new Category; $category->translate('fr')->setName('Chaussures'); $category->translate('en')->setName('Shoes'); $em->persist($category); // In order to persist new translations, call mergeNewTranslations method, before flush $category->mergeNewTranslations(); $category->translate('en')->getName();
猜测当前区域设置
你可以通过提供一个可调用的对象作为其第一个参数来配置订阅者猜测当前区域设置的方式。此库提供了一个可调用的对象(Knp\DoctrineBehaviors\ORM\Translatable\CurrentLocaleCallable
),它使用Symfony2返回当前区域设置。
代理翻译
一个额外功能允许你代理可翻译实体的翻译字段。
你可以在可翻译实体的__call
魔法方法中使用它,这样当尝试调用getName
(例如)时,它会返回当前区域设置的name翻译值。
<?php public function __call($method, $arguments) { return $this->proxyCurrentLocaleTranslation($method, $arguments); }
软删除
<?php $category = new Category; $em->persist($category); $em->flush(); // get id $id = $category->getId(); // now remove it $em->remove($category); $em->flush(); // hey, i'm still here: $category = $em->getRepository('Category')->findOneById($id); // but i'm "deleted" $category->isDeleted(); // === true
<?php $category = new Category; $em->persist($category); $em->flush(); // I'll delete you tomorow $category->setDeletedAt((new \DateTime())->modify('+1 day')); // Ok, I'm here $category->isDeleted(); // === false /* * 24 hours later... */ // Ok I'm deleted $category->isDeleted(); // === true
时间戳
<?php $category = new Category; $em->persist($category); $em->flush(); $id = $category->getId(); $category = $em->getRepository('Category')->findOneById($id); $category->getCreatedAt(); $category->getUpdatedAt();
责任归属
Blameable 可以跟踪给定实体的创建者和更新者。一个可调用的 callable 用于从您的应用程序中获取当前用户。
如果您使用 Doctrine 实体来表示您的用户,您可以配置订阅者来自动管理此用户实体与您的实体之间的关联。
使用 symfony2,您只需要配置名为 %knp.doctrine_behaviors.blameable_subscriber.user_entity%
的 DI 参数,例如
# app/config/config.yml
parameters:
knp.doctrine_behaviors.blameable_subscriber.user_entity: AppBundle\Entity\User
然后,您可以像这样使用它
<?php $category = new Category; $em->persist($category); // instances of %knp.doctrine_behaviors.blameable_subscriber.user_entity% $creator = $em->getCreatedBy(); $updater = $em->getUpdatedBy();
可记录的
Loggable 可以跟踪生命周期修改并使用任何第三方日志系统记录它们。一个可调用的 callable 用于从任何地方获取记录器。
<?php /** * @ORM\Entity */ class Category { use ORMBehaviors\Loggable\Loggable; // you can override the default log messages defined in trait: public function getUpdateLogMessage(array $changeSets = []) { return 'Changed: '.print_r($changeSets, true); } public function getRemoveLogMessage() { return 'removed!'; } }
然后,将这些消息传递到配置的可调用者。您可以通过向 LoggableSubscriber 传递另一个可调用者来定义自己的。
<?php $em->getEventManager()->addEventSubscriber( new \Knp\DoctrineBehaviors\ORM\Loggable\LoggableSubscriber( new ClassAnalyzer, function($message) { // do stuff with message } ) );
如果您使用 symfony,您也可以配置要使用的可调用者
// app/config/config.yml
parameters:
knp.doctrine_behaviors.loggable_subscriber.logger_callable.class: Your\InvokableClass
地理编码的
Geocodable 为 PostgreSQL 平台提供扩展,以便与 cube 和 earthdistance 扩展一起工作。
它允许您根据地理坐标查询实体。它还提供了一个易于使用的入口点,用于使用第三方库(如出色的 geocoder)将地址转换为纬度和经度。
<?php $geocoder = new \Geocoder\Geocoder; // register geocoder providers // $subscriber instanceof GeocodableSubscriber (add "knp.doctrine_behaviors.geocodable_subscriber" into your services.yml) $subscriber->setGeolocationCallable(function($entity) use($geocoder) { $location = $geocoder->geocode($entity->getAddress()); return new Point( $location->getLatitude(), $location->getLongitude() )); }); $category = new Category; $em->persist($category); $location = $category->getLocation(); // instanceof Point // find cities in a cricle of 500 km around point 47 lon., 7 lat. $nearCities = $repository->findByDistance(new Point(47, 7), 500);
可短语的
Sluggable 为实体生成短语(不保证唯一性)。将在更新/持久化时自动生成(您可以通过覆盖 getRegenerateSlugOnUpdate
返回 false 来禁用更新生成。您还可以通过覆盖 getSlugDelimiter
来覆盖默认的短划线分隔符。用例包括 SEO(例如,URL 如 http://mysite.com/post/3/introduction-to-php)
<?php use Doctrine\ORM\Mapping as ORM; use Knp\DoctrineBehaviors\Model as ORMBehaviors; /** * @ORM\Entity */ class BlogPost { use ORMBehaviors\Sluggable\Sluggable; /** * @ORM\Column(type="string") */ protected $title; public function getSluggableFields() { return [ 'title' ]; } }
可过滤的
Filterable 可以在仓储级别使用
它允许我们简单地过滤结果
连接过滤示例
<?php use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="ProductRepository") */ class ProductEntity { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type="string", nullable=true) */ private $name; /** * @ORM\Column(type="integer") */ private $code; /** * @ORM\OneToMany(targetEntity="Order", mappedBy="product") */ protected $orders; }
和仓储
<?php use Knp\DoctrineBehaviors\ORM\Filterable; use Doctrine\ORM\EntityRepository; class ProductRepository extends EntityRepository { use Filterable\FilterableRepository; public function getLikeFilterColumns() { return ['e:name', 'o:code']; } public function getEqualFilterColumns() { return []; } protected function createFilterQueryBuilder() { return $this ->createQueryBuilder('e') ->leftJoin('e.orders', 'o'); } }
现在我们可以使用以下方式过滤
$products = $em->getRepository('Product')->filterBy(['o:code' => '21']);
可调用者
可调用者被一些订阅者(如 blameable 和 geocodable)用于根据第三方系统填充信息。
例如,blameable 可调用者可以是任何实现 __invoke
方法的 symfony2 服务或任何匿名函数,只要它们返回当前登录用户表示(这意味着一切,一个用户实体,一个字符串,一个用户名,...)。有关被调用的 DI 服务的示例,请参阅 Knp\DoctrineBehaviors\ORM\Blameable\UserCallable
类。
在 geocodable 的情况下,您可以将其设置为任何实现 __invoke
的服务或返回 Knp\DoctrineBehaviors\ORM\Geocodable\Type\Point
对象的匿名函数。