composer package updates
[openemr.git] / vendor / adldap2 / adldap2 / docs / models / model.md
blob5e06bb884e284afb4ae0379e45cc3542c78218c0
1 # Models
3 - [Creating](#creating)
4     - [Available Make Methods](#available-make-methods)
5 - [Saving](#saving)
6     - [Creating Manually](#creating-manually)
7     - [Updating Manually](#updating-manually)
8 - [Checking Existence](#checking-existence)
9 - [Attributes](#attributes)
10     - [Getting Attributes](#getting-attributes)
11     - [Using a Getter](#using-a-getter)
12         - [Available Getters](#available-getters-on-all-models)
13     - [Getting Dirty Attributes](#getting-dirty-modified-attributes)
14     - [Getting Original Attributes](#getting-original-unmodified-attributes)
15     - [Setting Attributes](#setting-attributes)
16     - [Creating Attributes](#creating-attributes)
17     - [Updating Attributes](#updating-attributes)
18     - [Removing Attributes](#removing-attributes)
19     - [Checking Attributes](#checking-attributes)
20         - [Checking Existence of Attributes](#checking-existence-of-attributes)
21         - [Counting the Models Attributes](#counting-the-models-attributes)
22         - [Checking if a Model is Writable](#checking-if-a-model-is-writable)
23     - [Force Re-Syncing Attributes](#force-re-syncing-a-models-attributes)
24 - [Moving / Renaming](#moving--renaming)
25 - [Deleting](#deleting)
26 - [Extending (Custom Models)](#extending)
28 ## Creating
30 Creating LDAP entries manually is always a pain, but Adldap2 makes it effortless. Let's get started.
32 When you have a provider instance, call the `make()` method. This returns an `Adldap\Models\Factory` instance:
34 ```php
35 $factory = $provider->make();
36 ```
38 Or you can chain all methods if you'd prefer:
40 ```php
41 $user = $provider->make()->user();
42 ```
44 ### Available Make Methods:
46 When calling a make method, all of them accept an `$attributes` parameter
47 to fill the model with your specified attributes.
49 ```php
50 // Adldap\Models\User
51 $user = $provider->make()->user([
52     'cn' => 'John Doe',
53 ]);
55 // Adldap\Models\Computer
56 $computer = $provider->make()->computer([
57     'cn' => 'COMP-101',
58 ]);
60 // Adldap\Models\Contact
61 $contact = $provider->make()->contact([
62     'cn' => 'Suzy Doe',
63 ]);
65 // Adldap\Models\Container
66 $container = $provider->make()->container([
67     'cn' => 'VPN Users',
68 ]);
70 // Adldap\Models\Group
71 $group = $provider->make()->group([
72     'cn' => 'Managers',
73 ]);
75 // Adldap\Models\OrganizationalUnit
76 $ou = $provider->make()->ou([
77     'name' => 'Acme',
78 ]);
79 ```
81 ## Saving
83 When you have any model instance, you can call the `save()` method to persist the
84 changes to your server. This method returns a `boolean`. For example:
86 ```php
87 $user = $provider->make()->user([
88     'cn' => 'New User',
89 ]);
91 if ($user->save()) {
92     // User was saved.
93 } else {
94     // There was an issue saving this user.
96 ```
98 > **Note**: When a model is saved successfully (whether created or updated),
99 > the models attributes are re-synced in the background from your AD.
101 > This allows you to perform other operations during the same
102 > request that require an existing model.
104 ### Creating (Manually)
106 If you are sure the model **does not exist** already inside your AD, you can use the `create()` method:
108 ```php
109 $user = $provider->make()->user([
110     'cn' => 'New User',
113 if ($user->create()) {
114     // User was created.
115 } else {
116     // There was an issue creating this user.
120 > **Note**: When you call the create method, if the model does not have a
121 > distinguished name, one will automatically be generated for you using your
122 > `base_dn` set in your configuration and the models common name.
124 ### Updating (Manually)
126 If you are sure the model **does exist** already inside your AD, you can use the `update()` method:
128 ```php
129 $user = $provider->search()->whereEquals('cn', 'John Doe')->firstOrFail();
131 $user->displayName = 'Suzy Doe';
133 if ($user->update()) {
134     // User was updated.
135 } else {
136     // There was an issue updating this user.
140 ## Checking Existence
142 If you need to check the existence of a model, use the property `exists`.
144 How does it know if the model exists in AD? Well, when models are constructed from
145 search results, the `exists` property on the model is set to `true`.
147 ```php
148 $user = $provider->search()->find('jdoe');
150 $user->exists; // Returns true.
152 if ($user->delete()) {
154     $user->exists; // Returns false.
159 If a model is created successfully, the `exists` property is set to `true`:
161 ```php
162 $user = $provider->make()->user([
163     'cn' => 'John Doe',
166 $user->exists; // Returns false.
168 if ($user->save()) {
169     
170     $user->exists; // Returns true.
171     
175 ## Attributes
177 Since all models extend from the base class `Adldap\Models\Model`, there are many
178 useful methods that you can utilize on every model.
180 ### Getting Attributes
182 You can get attributes in a few ways:
184 ```php
185 // Returns an array all of the users attributes.
186 $user->getAttributes();
188 // Returns an array of all the users email addresses.
189 // Returns `null` if non-existent.
190 $user->getAttribute('mail');
192 // Returns the users first email address.
193 // Returns `null` if non-existent.
194 $user->getAttribute('mail', 0);
196 // Returns the users first email address.
197 // Returns `null` if non-existent.
198 $user->getFirstAttribute('mail');
200 // Returns an array of all the users email addresses. 
201 $user->mail;
203 // Returns the users first email address.
204 $user->mail[0];
207 #### Using a Getter
209 Some attributes have methods for easier retrieval so you don't need to look up the LDAP attribute name.
211 For example, to retrieve a users email address, use the method `getEmail()`:
213 ```php
214 $user->getEmail();
217 Or to retrieve all of a users email addresses, use the method `getEmails()`:
219 ```php
220 $user->getEmails();
223 ##### Available Getters on All Models
225 The following methods are available on all returned models:
227 ```php
228 // Returns the model's 'name' attribute.
229 $model->getName();
231 // Returns the model's 'cn' attribute.
232 $model->getCommonName();
234 // Returns the model's 'displayname' attribute.
235 $model->getDisplayName();
237 // Returns the model's 'samaccountname' attriubte.
238 $model->getAccountName();
240 // Returns the model's 'samaccounttype` attribute.
241 $model->getAccountType();
243 // Returns the model's 'whencreated` attribute.
244 $model->getCreatedAt();
246 // Returns the model's 'whencreated` attribute in a MySQL timestamp format.
247 $model->getCreatedAtDate();
249 // Returns the model's 'whencreated' attribute in unix time.
250 $model->getCreatedAtTimestamp();
252 // Returns the model's 'whenchanged` attribute.
253 $model->getUpdatedAt();
255 // Returns the model's 'whenchanged` attribute in a MySQL timestamp format.
256 $model->getUpdatedAtDate();
258 // Returns the model's 'whenchanged` attribute in unix time.
259 $model->getUpdatedAtTimestamp();
261 // Returns the model's 'objectclass' attribute.
262 $model->getObjectClass();
264 // Returns the model's root object category string.
265 $model->getObjectCategory();
267 // Returns the model's object category in an array.
268 $model->getObjectCategoryArray();
270 // Returns the model's object category distinguished name.
271 $model->getObjectCategoryDn();
273 // Returns the model's SID in binary.
274 $model->getObjectSid();
276 // Returns the model's GUID in binary.
277 $model->getObjectGuid();
279 // Returns the model's SID in a string.
280 $model->getConvertedSid();
282 // Returns the model's GUID in a string.
283 $model->getConvertedGuid();
285 // Returns the model's primary group ID.
286 $model->getPrimaryGroupId();
288 // Returns the model's 'instancetype' attribute.
289 $model->getInstanceType();
291 // Returns the model's 'maxpwdage' attribute.
292 $model->getMaxPasswordAge();
295 For more documentation on specific getters, please take a look at the relevant model documentation.
297 #### Getting Dirty (Modified) Attributes
299 You can get a models modified attributes using the `getDirty()` method:
301 ```php
302 $user = $provider->search()->users()->find('john');
304 // Returns array [0 => 'John Doe']
305 var_dump($user->cn);
307 $user->setAttribute('cn', 'Jane Doe');
309 // Returns array ['cn' => [0 => 'Jane Doe']]
310 var_dump($user->getDirty());
312 // The attribute has been modified - returns array [0 => 'Jane Doe']
313 var_dump($user->cn);
316 The method returns an array with the key being the modified attribute,
317 and the array being the new values of the attribute.
319 #### Getting Original (Unmodified) Attributes
321 You can get a models original attributes using the `getOriginal()` method:
323 ```php
324 $user = $provider->search()->users()->find('john');
326 // Returns array [0 => 'John Doe']
327 var_dump($user->cn);
329 $user->setAttribute('cn', 'Jane Doe');
331 // The attribute has been modified - returns array [0 => 'Jane Doe']
332 var_dump($user->cn);
334 // Retrieving the original value - returns array [0 => 'John Doe']
335 var_dump($user->getOriginal()['cn']);
338 > **Note**: Keep in mind, when you `save()` a model, the models original
339 > attributes will be re-synchronized to the models new attributes.
341 ### Setting Attributes
343 Just like getting model attributes, there's multiple ways of setting attributes as well:
345 ```php
346 // Setting via method:
347 $user->setAttribute('cn', 'John Doe');
349 // Specifying a subkey for overwriting specific attributes:
350 $user->setAttribute('mail', 'other-mail@mail.com', 0);
352 // Setting the first attribute:
353 $user->setFirstAttribute('mail', 'jdoe@mail.com');
355 // Setting via property:
356 $user->cn = 'John Doe';
358 // Mass setting attributes:
359 $user->fill([
360     'cn' => 'John Doe',
361     'mail' => 'jdoe@mail.com',
365 ### Creating Attributes
367 To create an attribute that does not exist on the model, you can set it like a regular property:
369 ```php
370 $user = $provider->search()->whereEquals('cn', 'John Doe')->firstOrFail();
372 $user->new = 'New Attribute';
374 $user->save();
377 If the set attribute does not exist on the model already,
378 it will automatically be created when you call the `save()` method.
380 If you'd like manually create new attributes individually, call the `createAttribute($attribute, $value)` method:
382 ```php
383 if ($user->createAttribute('new', 'New Attribute')) {
384     // Attribute created.
388 ### Updating Attributes
390 To modify an attribute you can either use a setter method, or by setting it manually:
392 > **Note**: You can also utilize setters to create new attributes if your model does not already have the attribute.
394 ```php
395 $user = $provider->search()->whereEquals('cn', 'John Doe')->firstOrFail();
397 $user->cn = 'New Name';
399 // Or use a setter:
401 $user->setCommonName('New Name');
403 $user->save();
406 If you'd like to update attributes individually, call the `updateAttribute($attribute, $value)` method:
408 ```php
409 if ($user->updateAttribute('cn', 'New Name')) {
410     // Successfully updated attribute.
414 ### Removing Attributes
416 To remove attributes, set the attribute to `NULL`:
418 ```php
419 $user->cn = null;
421 $user->save();
424 Or, you can call the `deleteAttribute($attribute)` method:
426 ```php
427 if ($user->deleteAttribute('cn')) {
428     // Attribute has been deleted.
432 ### Checking Attributes
434 #### Checking Existence of Attributes
436 To see if a model contains an attribute, use the method `hasAttribute()`:
438 ```php
439 // Checking if a base attribute exists:
440 if ($user->hasAttribute('mail')) {
442     // This user contains an email address.
446 // Checking if a sub attribute exists, by key:
447 if ($user->hasAttribute('mail', 1)) {
449     // This user contains a second email address.
454 #### Counting the Models Attributes
456 To retrieve the total number of attributes, use the method `countAttributes()`:
458 ```php
459 $count = $user->countAttributes();
461 var_dump($count); // Returns int
464 #### Checking if a Model is contained in an OU
466 To check if a model is located inside an OU, use the `inOu()` method:
468 ```php
469 if ($model->inOu('User Accounts')) {
470     // This model is inside the 'User Accounts' OU.
474 You can also use an OU model instance:
476 ```php
477 $serviceAccounts = $provider->search()->ous()->find('Service Accounts');
479 if ($model->inOu($serviceAccounts)) {
480     // This model is inside the 'Service Accounts' OU.
484 #### Checking if a Model is Writable
486 To check if the model can be written to, use the method `isWritable()`:
488 ```php
489 if ($model->isWritable()) {
491     // You can modify this model.
492     
496 ### Force Re-Syncing A Models Attributes
498 If you need to forcefully re-sync a models attributes, use the method `syncRaw()`:
500 ```php
501 $user->syncRaw();
504 > **Note**: This will query your AD server for the current model, and re-synchronize
505 > it's attributes. This is only recommended if your creating / updating / deleting
506 > attributes manually through your LDAP connection.
508 ## Moving / Renaming
510 To move a user from one DN or OU to another, use the `move($newRdn, $newParentDn)` method:
512 ```php
513 // New Relative distinguished name.
514 $newRdn = 'cn=John Doe';
516 // New parent distiguished name.
517 $newParentDn = 'OU=New Ou,DC=corp,DC=local';
519 if ($user->move($newRdn, $newParentDn)) {
520     // User was successfully moved to the new OU.
524 If you would like to keep the models old RDN along side their new RDN, pass in false in the last parameter:
526 ```php
527 // New Relative distinguished name.
528 $newRdn = 'cn=John Doe';
530 // New parent distiguished name.
531 $newParentDn = 'OU=New Ou,DC=corp,DC=local';
533 if ($user->move($newRdn, $newParentDn, $deleteOldRdn = false)) {
534     // User was successfully moved to the new OU,
535     // and their old RDN has been left in-tact.
539 To rename a users DN, just pass in their new relative distinguished name in the `rename($newRdn)` method:
541 ```php
542 $newRdn = 'cn=New Name';
544 if ($user->rename($newRdn)) {
545     // User was successfully renamed.
549 > **Note**: The `rename()` method is actually an alias for the `move()` method.
551 ## Deleting
553 To delete a model, just call the `delete()` method:
555 ```php
556 $user = $provider->search()->whereEquals('cn', 'John Doe')->firstOrFail();
558 echo $user->exists; // Returns true.
560 if ($user->delete()) {
561     // Successfully deleted user.
563     echo $user->exists; // Returns false.
567 ## Extending
569 > **Note**: This feature was introduced in `v8.0.0`.
571 To use your own models, you will need to create a new [Schema](../schema.md).
573 Once you have created your own schema, you must insert it inside the construct of your provider.
575 Let's walk through this process.
577 First we'll create our model we'd like to extend / override:
579 > **Note**: Your custom model **must** extend from an existing Adldap2 model.
580 > This is due to methods and attributes that only exist on these classes.
582 ```php
583 namespace App\Ldap\Models;
585 use Adldap\Models\User as Model;
587 class User extends Model
589     public function getCommonName()
590     {
591         // Overriding model method.
592     }
596 Now, we'll create our custom schema and return our models class name:
598 ```php
599 namespace App\Ldap\Schemas;
601 use App\Ldap\Models\User;
603 class LdapSchema extends ActiveDirectory
605     public function userModel()
606     {
607         return User::class;
608     }
612 Finally, when we create a provider, we need to insert our Schema into the constructor:
614 ```php
615 use Adldap\Connections\Provider;
617 $schema = new LdapSchema();
619 $provider = new Provider($config, $connection = null, $schema);
621 $provider->connect();
623 // If `jdoe` exists, your custom model will be returned.
624 $user = $provider->search()->users()->find('jdoe');