The bundle provides new Doctrine type and Schema to simplify the way you store the Subscription objects with Doctrine.
Using The Doctrine Mapping
Configuration
To enable this feature, the following configuration option shall be set:
webpush:doctrine_mapping:true
This will tell the bundle to register the Subscription object as a Doctrine mapped-superclass. The DoctrineBundle shall be enabled. No additional configuration is required.
The Subscription Entity
First of all, we need to create a Subscription Entity that extends the Subscription object. In this example, we also need to associate one or more Subscription entities to a specific user (Many To One relationship).
src/Entity/Subscription.php
<?phpdeclare(strict_types=1);namespaceApp\Entity;useDoctrine\ORM\Mappingas ORM;useWebPush\Subscriptionas WebPushSubscription;/** * @ORM\Table(name="subscriptions") * @ORM\Entity */classSubscriptionextendsWebPushSubscription{/** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */private?int $id =null;/** * @ORM\ManyToOne(targetEntity="User", inversedBy="subscriptions", cascade={"persist"}) * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable="true") */private?User $user;publicfunctiongetId():?int {return$this->id; }publicfunctiongetUser():?User {return$this->user; }publicfunctionsetUser(?User $user):self {$this->user = $user;return$this; }// We need to override this method as it returns a WebPush\Subscription and we want an entitypublicstaticfunctioncreateFromString(string $input):self { $base =BaseSubscription::createFromString($input); $object =newself($base->getEndpoint()); $object->withContentEncodings($base->getSupportedContentEncodings());foreach ($base->getKeys()->all()as $k => $v) { $object->getKeys()->set($k, $v); }return $object; }}
In this exaple, we assume you already have a valid User entity class.
The User Entity
Now, to have a bidirectional relationship between this class and the User entity class, we will add this relationship to the User class.
Now that your entities are set, you can register Subcriptions and assign them to your users. To send a Notification to a specific user, you just have to get all subscriptions using $user->getSubscriptions().
$subscriptions = $user->getSubscriptions();foreach ($subscriptions as $subscription) { $report =$this->webPush->send($notification, $subscription);if ($report->subscriptionExpired()) {//...Remove this subscription }}
Using Doctrine Type
The bundle auto-register the Doctrine type webpush_subscription. The Subscription object will automatically be converted.
Starting with v1.1, it is possible to use your own Subscription entity class. The only constraint is that it shall implement the interface WebPush\SubscriptionInterface or shall have a method that returns an object that implements this interface.