xp-framework / ldap

XP Framework 的 LDAP 支持

v9.1.1 2022-11-02 14:30 UTC

README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.0+ Supports PHP 8.0+ Latest Stable Version

peer.ldap 包实现了对 LDAP (轻量级目录访问协议) 的访问。

示例(LDAP 搜索)

use peer\ldap\LDAPConnection;
use util\cmd\Console;

$l= new LDAPConnection('ldap://ldap.example.com');
$l->connect();

$search= $l->search(
  'ou=People,dc=OpenLDAP,dc=Org', 
  '(objectClass=*)'
);
  
Console::writeLinef('===> %d entries found', $search->numEntries());
foreach ($search as $result) {
  Console::writeLine('---> ', $result->toString());
}

$l->close();

示例(修改条目)

use peer\ldap\{LDAPConnection, LDAPEntry};

$l= new LDAPConnection('ldap://uid=admin,o=roles,dc=planet-xp,dc=net:password@ldap.example.com');
$l->connect();

with ($entry= $l->read(new LDAPEntry('uid=1549,o=people,dc=planet-xp,dc=net'))); {
  $entry->setAttribute('firstname', 'Timm');

  $l->modify($entry);
}

$l->close();

示例(添加条目)

use peer\ldap\{LDAPConnection, LDAPEntry};

$l= new LDAPConnection('ldap://uid=admin,o=roles,dc=planet-xp,dc=net:password@ldap.example.com');
$l->connect();

with ($entry= new LDAPEntry('uid=1549,o=people,dc=planet-xp,dc=net')); {
  $entry->setAttribute('uid', 1549);
  $entry->setAttribute('firstname', 'Timm');
  $entry->setAttribute('lastname', 'Friebe');
  $entry->setAttribute('objectClass', 'xpPerson');

  $l->add($entry);
}

$l->close();

动态创建 LDAP 查询

如果需要动态构建 LDAP 查询,LDAPQuery 类提供了一个类似于 printf 的语法来实现这一点。

use peer\ldap\LDAPQuery;

$res= $ldap->searchBy(new LDAPQuery(
  'o=people,dc=planet-xp,dc=net',
  '(&(objectClass=%c)(|(username=%s)(uid=%d)))',
  'xpPerson',
  'friebe'
  1549
));

当使用 "%s" 标记时,传递的值将根据 LDAP 查询语法中的规则进行转义。%c 标记按原样复制,而 %d 将参数作为数值处理。