@@ -98,16 +98,60 @@ $apiKey = request()->attributes->get('apikey');
9898```
9999
100100
101- ## Leveraging the ApiKey name as a foreign key
101+ ## Using foreign keys to ApiKey
102102
103- It stands to reason that in many cases one API key will be issued for exactly one user.
104- But to enforce referential integrity a join would be required at run time. This is certainly
105- possible, but it would complicate this repository. So, it is recommended that if you need to
106- associate a user to an ApiKey you do so by naming the ApiKey the primary key of the user.
107- You can then join the two entities using an ` ON ` statement.
103+ Because an ApiKey can be regenerated, there may be no reason to assign multiple
104+ API keys to the same entity. For instance, if each Customer has a 1:1 with ApiKey
105+ then you can safely disable that key, regenerate it, and so on; never needing to
106+ assign a new ApiKey.
108107
109- The ApiKey name column is unique and indexed and perfectly suited for this approach.
108+ To dynamically create a 1:1 relationship between a Customer entity and API key,
109+ create an event subscriber:
110110
111+ ``` php
112+ <?php
113+
114+ declare(strict_types=1);
115+
116+ namespace App\ORM\Event\Subscriber;
117+
118+ use ApiSkeletons\Laravel\Doctrine\ApiKey\Entity\ApiKey;
119+ use App\ORM\Entity\Customer;
120+ use Doctrine\Common\EventSubscriber;
121+ use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
122+ use Doctrine\ORM\Events;
123+
124+ class ApiKeyEventSubscriber implements
125+ EventSubscriber
126+ {
127+ /**
128+ * {@inheritDoc}
129+ */
130+ public function getSubscribedEvents()
131+ {
132+ return [
133+ Events::loadClassMetadata,
134+ ];
135+ }
136+
137+ public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
138+ {
139+ // the $metadata is the whole mapping info for this class
140+ $metadata = $eventArgs->getClassMetadata();
141+
142+ switch ($metadata->getName()) {
143+ case Customer::class:
144+ $metadata->mapOneToOne([
145+ 'targetEntity' => ApiKey::class,
146+ 'fieldName' => 'apiKey',
147+ ]);
148+ break;
149+ default:
150+ break;
151+ }
152+ }
153+ }
154+ ```
111155
112156
113157## Event Logging
0 commit comments