real-chocopanda/glorpen-propel-event-bundle

为 Symfony2 提供 Propel 事件。此包允许你在对象/查询创建时注入服务,在保存前从服务设置数据等。

dev-master 2012-08-13 13:00 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:14:17 UTC


README

Symfony2 中的 Propel 事件。

使用 Symfony2 2.1

要使用此包与 2.1 版本,您必须覆盖参数 dispatcher.class 为

<parameter key="glorpen.propel.event.dispatcher.class">Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher</parameter>

如何安装

app/AppKernel.php

<?php

class AppKernel extends AppKernel
{
   public function registerBundles()
   {
       $bundles = array(
           ...
           new Glorpen\PropelEvent\PropelEventBundle\PropelEventBundle(),
           ...
       );
   }
}
  • 将行为添加到 propel 配置(如果您想在 propel 的后/前钩子上使用事件)

或者您也可以导入 PropelEventBundle/Resources/config/propel_config.yml 以定义类

propel:
   build_properties:
     propel.behavior.event.class: 'src.Glorpen.PropelEvent.PropelEventBundle.behavior.EventBehavior'
     propel.behavior.default: "event"

监听 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>

自定义事件

您可以使用通用或自定义 Event 类来触发事件,以下示例中为 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\PropelEvent\PropelEventBundle\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));
   }
}