Doctrine
This section explains how to store Subscription objects using Doctrine ORM in your Symfony application.
Creating a Subscription Entity
To persist subscriptions in your database, you need to create a Doctrine entity. There are two approaches:
Extend the base
WebPush\Subscriptionclass (recommended for simplicity)Implement the
WebPush\SubscriptionInterfaceinterface (more flexibility)
Approach 1: Extending the Base Class
In this example, we create a Subscription entity that extends the base WebPush\Subscription class. We also associate one or more Subscription entities to a specific user (Many-To-One relationship).
<?php
declare(strict_types=1);
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use WebPush\Subscription as WebPushSubscription;
#[ORM\Table(name: 'subscriptions')]
#[ORM\Entity]
class Subscription extends WebPushSubscription
{
#[ORM\Id]
#[ORM\Column(type: 'integer')]
#[ORM\GeneratedValue(strategy: 'AUTO')]
private ?int $id = null;
#[ORM\ManyToOne(targetEntity: User::class, cascade: ['persist'], inversedBy: 'subscriptions')]
#[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', nullable: true)]
private ?User $user;
public function getId(): ?int
{
return $this->id;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
// We need to override this method as it returns a WebPush\Subscription and we want an entity
public static function createFromString(string $input): self
{
$base = parent::createFromString($input);
$object = new self($base->getEndpoint());
$object->withContentEncodings($base->getSupportedContentEncodings());
foreach ($base->getKeys() as $k => $v) {
$object->setKey($k, $v);
}
return $object;
}
}The User Entity
User EntityNow, to have a bidirectional relationship between this class and the User entity class, we will add this relationship to the User class.
Sending Notifications To A User
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().
Approach 2: Implementing the Interface Directly
Instead of extending the WebPush\Subscription class, you can create your own entity class that implements the WebPush\SubscriptionInterface interface. This approach gives you more flexibility in how you structure your entity.
Both approaches (extending the class or implementing the interface) are valid and can be used depending on your needs.
Last updated
Was this helpful?