PHP code example of pcz / deferred-kdyby-events

1. Go to this page and download the library: Download pcz/deferred-kdyby-events library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pcz / deferred-kdyby-events example snippets


use Doctrine\ORM\Mapping as ORM;

/** @ORM\Entity */
class ChangeProductPriceEvent extends \pcz\DeferredKdybyEvents\DeferredEvent {

	const EVENT_NAME = 'ChangeProductPrice';

	/**
	 * @var Product
	 * @ORM\ManyToOne(targetEntity="Product")
	 */
	protected $product;

	/**
	 * @var integer
	 * @ORM\Column(type="integer")
	 */
	protected $new_price;

	public function __construct(\DateTime $execution_date, Product $product, $new_price) {
		parent::__construct($execution_date);
		$this->product = $product;
		$this->new_price = $new_price;
	}

	public function getEventName() {
		return self::EVENT_NAME;
	}

	public function getProduct() { return $this->product; }

	public function getNewPrice() { return $this->new_price; }

}

/** @var $em Kdyby\Doctrine\EntityManager */

/** @var $product Product */

$event = new ChangeProductPriceEvent(
	new \DateTime('2016-04-01 00:00:00'),
	$product,
	10
);

$em->persist($event);
$em->flush();

class ChangeProductEventListener implements Kdyby\Events\Subscriber {

	// this listener must be registered in config, with 'kdyby.subscriber' tag of course

	/** @var Kdyby\Doctrine\EntityManager */
	protected $em;

	public function getSubscribedEvents() {
		return [ChangeProductPriceEvent::EVENT_NAME     =>  'changePrice'];
	}

	public function changePrice(ChangeProductPriceEvent $e) {
		// don't use this in production, some locking should be implemented
		$product = $e->getProduct();
		$product->setPrice($e->getNewPrice());
		$this->em->persist($product)->flush();
	}

}

/** @pcz\DeferredKdybyEvents\Annotations\Keeping */
class NewMessageNotificationEvent extends pcz\DeferredKdybyEvents\GroupedDeferredEvent {
	// ...

	protected $user;

	public function __construct(\DateTime $execution_date, User $user) {
		parent::__construct($execution_date);
		$this->user = $user;
	}

	public function getGroupKey() {
		return $this->user->getId();
	}
	
	// ...
}

class RemoveUserFromRoomEvent extends pcz\DeferredKdybyEvents\GroupedDeferredEvent {
	// ...

	public function getGroupKey() {
		return $this->user->getId() . '_' . $this->room->getId();
	}

	// ...
}