karser / glorpen-propel-bundle
为Symfony2提供Propel事件和模型扩展。
Requires
- propel/propel-bundle: 1.*
- symfony/symfony: <3.0
Requires (Dev)
- phpunit/phpunit: *
- propel/propel-bundle: >=1.4.4
README
为Symfony2提供额外的Propel集成。
官方仓库
用于分支和其他有趣的事情
BitBucket: https://bitbucket.org/glorpen/glorpenpropelbundle - 主仓库
GitHub: https://github.com/glorpen/GlorpenPropelBundle
如何安装
- 将需求添加到composer.json
{ "require": { "glorpen/propel-bundle": "@dev" } }
- 在你的 AppKernel 类中启用插件
app/AppKernel.php
<?php class AppKernel extends AppKernel { public function registerBundles() { $bundles = array( ... new Glorpen\Propel\PropelBundle\GlorpenPropelBundle(), ... ); } }
- 将行为配置添加到propel配置
要一次性启用所有行为,可以将 @GlorpenPropelBundle/Resources/config/config.yml 和 config_dev.yml 分别导入到您的配置中。
例如,对于 config.yml
imports: - { resource: @GlorpenPropelBundle/Resources/config/config.yml }
Propel事件
如果您没有导入此包提供的 config.yml,您必须将 event 行为添加到您的propel配置,并更改 PropelPDO 类。
propel: build_properties: propel.behavior.event.class: 'vendor.glorpen.propel-bundle.Glorpen.Propel.PropelBundle.Behaviors.EventBehavior' propel.behavior.default: "event" dbal: classname: Glorpen\Propel\PropelBundle\Connection\EventPropelPDO
在 config_dev.yml
propel: dbal: classname: Glorpen\Propel\PropelBundle\Connection\EventDebugPDO
监听Propel钩子
- 注册监听器
<service class="SomeBundle\Listeners\HistoryBehaviorListener"> <argument type="service" id="security.context" /> <tag name="propel.event" /> </service> <service id="my.listener" class="SomeBundle\Listeners\HistoryBehaviorListener"> <tag name="propel.event" method="onPropelEventSave" event="model.save.post" /> </service>
可用事件
事件类:ConnectionEvent
- connection.create
- connection.commit.pre
- connection.commit.post
- connection.rollback.post
- connection.rollback.pre
事件类:ModelEvent
- model.insert.post
- model.update.post
- model.delete.post
- model.save.post
- model.insert.pre
- model.update.pre
- model.delete.pre
- model.save.pre
- model.construct
事件类:QueryEvent
- query.delete.pre
- query.delete.post
- query.select.pre
- query.update.pre
- query.update.post
- query.construct
事件类:PeerEvent
- construct
将在模型/查询/同伴构造/删除/更新等时调用
模型容器感知接口
您可以在模型上实现 ContainerAwareInterface 以通过内置服务访问 Container。Container 在 model.construct 事件中注入。
如果您遇到类似于“Serialization of 'Closure' is not allowed”的错误,这可能是由于模型中注入了某些不可序列化的服务(因为Propel偶尔会序列化和反序列化数据)。
<?php use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; class Something extends BaseSomething implements ContainerAwareInterface { private $someService; public function setContainer(ContainerInterface $container = null){ if($container) $this->someService = $this->container->get("some_service"); } }
事务事件
就像使用Doctrine @ORMHasLifecycleCallbacks 一样,您可以在数据库事务中处理模型中的非数据库逻辑。
提交钩子将在PDO事务提交之前运行,回滚将在回滚之前运行,并且仅在已保存的模型上(如果预提交钩子中抛出异常)。
- preCommit
- preCommitSave
- preCommitUpdate
- preCommitInsert
- preCommitDelete
- preRollback
- preRollbackSave
- preRollbackUpdate
- preRollbackInsert
- preRollbackDelete
请注意,当在大量模型对象上使用按需格式化并启用事务时,它们仍然会缓存在内置服务中,因此您可能会耗尽可用的PHP内存。
以下是如何使用可用钩子的示例(代码大部分来自Symfony2食谱)
<?php class SomeModel extends BaseSomeModel { public function preCommitSave(\PropelPDO $con = null){ $this->upload(); } public function preCommitDelete(\PropelPDO $con = null){ $this->removeUpload(); } public function preSave(\PropelPDO $con = null){ $this->preUpload(); return parent::preSave($con); } // code below is copied from https://symfony.ac.cn/doc/2.1/cookbook/doctrine/file_uploads.html public $file; public function preUpload(){ if (null !== $this->file){ // do whatever you want to generate a unique name $filename = sha1(uniqid(mt_rand(), true)); $this->path = $filename.'.'.$this->file->guessExtension(); } } public function upload(){ if (null === $this->path) return; // if there is an error when moving the file, an exception will // be automatically thrown by move(). This will properly prevent // the entity from being persisted to the database on error $this->file->move($this->getUploadRootDir(), $this->path); throw new \RuntimeException("file cannot be saved"); unset($this->path); } public function removeUpload(){ if ($file = $this->getAbsolutePath()){ unlink($file); } } }
自定义事件
您可以使用通用或自定义事件类触发事件,以下示例中为 ValidationEvent。
- 创建 ValidationEvent 事件
<?php namespace YourBundle\Events; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\EventDispatcher\Event; class ValidationEvent extends Event { private $metadata; public function __construct(ClassMetadata $metadata){ $this->metadata = $metadata; } /** * @return \Symfony\Component\Validator\Mapping\ClassMetadata */ public function getMetadata(){ return $this->metadata; } }
- 在 services.xml 中注册监听器
<service id="your.service" class="%your.service.class%"> <argument>%your.service.argument%</argument> <tag name="propel.event" method="onProductLoadValidatorMetadata" event="product.validation" /> </service>
- 然后在模型类中使用它
<?php namespace YourBundle\Model; use YourBundle\Events\ValidationEvent; use Glorpen\Propel\PropelBundle\\Dispatcher\EventDispatcherProxy; use Symfony\Component\Validator\Mapping\ClassMetadata; use YourBundle\Model\om\BaseProduct; class Product extends BaseProduct { public static function loadValidatorMetadata(ClassMetadata $metadata) { EventDispatcherProxy::trigger('product.validation', new ValidationEvent($metadata)); } }
模型扩展
如果您没有导入此包提供的 config.yml,您必须将 extend 行为添加到您的propel配置。
propel: build_properties: propel.behavior.extend.class: 'vendor.glorpen.propel-bundle.Glorpen.Propel.PropelBundle.Behaviors.ExtendBehavior' propel.behavior.default: "extend"
启用行为后,您可以为与Propel一起使用定义自定义模型类。
您只能以这种方式扩展模型类(不需要扩展Peers/Queries)。
对Query::find()、Peer::populateObject()等的调用现在将返回您扩展的类对象。
简而言之,它修复了以下问题
- 扩展其他包(例如FOSUserBundle)使用的模型类
- 返回正确实例的查询/Peer
- 在调用SomeQuery::create()时创建正确的Query实例
映射使用
在config.yml
glorpen_propel: extended_models: FOS\UserBundle\Propel\User: MyApp\MyBundle\Propel\User
动态/服务使用
您可以使用服务创建动态扩展。
您的服务应实现GlorpenPropelPropelBundleProviderOMClassProvider接口。
在services.xml
<service id="your.service" class="%your.service.class%"> <argument>%your.service.argument%</argument> <tag name="propel.om" /> </service>
FOSUserBundle和AdminGenerator
使用上述配置,您可以使用AdminGenerator为FOSUser生成后端,用于编辑/创建等。目前,您必须创建空的UserQuery和UserPeer类,然后用户模型后端的所有功能都应该正常工作:)
其他优点
PlainModelJoin
允许将数据注入ON子句,例如比较字段与日期或来自其他连接表的字段。
请记住,提供的值将原样添加,而不会进行别名解析和转义。
使用
<?php $relationAlias = 'WithoutCurrentSubscription'; $join = PlainModelJoin::create($this, 'Subscription', $relationAlias, \Criteria::LEFT_JOIN); //active items... $join->addCondition($relationAlias.'.starts_at', '"'.$now->format('Y-m-d H:i:s').'"', \Criteria::LESS_EQUAL); $join->addCondition($relationAlias.'.ends_at', '"'.$now->format('Y-m-d H:i:s').'"', \Criteria::GREATER_EQUAL); //...and inversion $this->where('WithoutCurrentSubscription.Id is null');