Working with DN strings are a pain, but they're about to get easier. Adldap includes a DN builder for easily modifying and creating DN strings.
Note: All values inserted into DN methods are escaped. You don't need to escape any values before hand.
To create a new DN, construct a new \Adldap\Objects\DistinguishedName
instance:
$dn = new \Adldap\Objects\DistinguishedName();
You can also pass in a current DN string and start modifying it:
$currentDn = 'cn=John Doe,ou=Accounting,dc=corp,dc=acme,dc=org';
$dn = new \Adldap\Objects\DistinguishedName($currentDn);
// Add Domain Component
$dn->addDc('corp');
// Remove Domain Component
$dn->removeDc('corp');
// Add Organizational Unit
$dn->addOu('Accounting');
// Remove Organizational Unit
$dn->removeOu('Accounting');
// Add Common Name
$dn->addCn('John Doe');
// Remove Common Name
$dn->removeCn('John Doe');
If you'd like to set the base DN, such as a domain component RDN, use the setBase()
method:
$base = 'dc=corp,dc=acme,dc=org';
$dn->setBase($base);
When you're creating a new AD record, you'll need to create a distinguished name as well. Let's go through an example of creating a new user.
$user = $provider->make()->user();
$user->setCommonName('John Doe');
$user->setFirstName('John');
$user->setLastName('Doe');
So we've set the basic information on the user, but we run into trouble when we want to put the user into a certain container (such as 'Accounting') which is done through the DN. Let's go through this example:
$dn = $user->getDnBuilder();
$dn->addCn($user->getCommonName());
$dn->addOu('Accounting');
$dn->addDc('corp');
$dn->addDc('acme');
$dn->addDc('org');
// Returns 'cn=John Doe,ou=Accounting,dc=corp,dc=acme,dc=org'
echo $dn->get();
// The DistinguishedName object also contains the __toString() magic method
// so you can also just echo the object itself
echo $dn;
Now we've built a DN, and all we have to do is set it on the new user:
$user->setDn($dn);
$user->save();
When you've received a model from a search result, you can build and modify the models DN like so:
$user = $ad->users()->find('jdoe');
$dn = $user->getDnBuilder();
$dn->addOu('Users');
$user->setDn($dn)->save();