How to use a PEAR library inside a custom namespace?

1.6k views Asked by At

I can't use a PEAR library when I have my custom namespace declared.

The namespace and the autoload function:

<?php
namespace ldapwrangler;
function autoload($class_name)
{
  $path = ROOT_DIR . "/inc/" . str_replace('\\', "/", $class_name) . ".class.php";    
  require_once($path);
}
spl_autoload_register('ldapwrangler\autoload');
?>

If I try something like this ROOT_DIR/inc/ldapwrangler/LDAP.class.php:

<?php
namespace ldapwrangler;
require_once 'Net/LDAP2.php';

class LDAP{
    protected $connection;
    protected $defaultSearchBase;

    /**
     * @param $conf conf array containing ldap direction login and server.
     */
    function __construct($conf)
    {
        $this->connection = $this->set_connection($conf);
        $this->defaultSearchBase = $conf['basedn'];
    }
    /**
     * Bind to the directory configured in the $conf array
     * 
     * @param $conf conf array containing ldap direction login and server.
     */ 
    function set_connection($conf)
    {
        $ldap = Net_LDAP2::connect($conf);

        // Testing for connection error
        if (PEAR::isError($ldap)) {
            $msg = 'Could not connect to LDAP server: '.$ldap->getMessage();
            Logging::log_message('error',$msg);
            return false;
        }
        return $ldap;
    }

    //rest of the class...
    }
?>

I get an error like this:

May 29 10:03:32 reagand-desktop apache2: PHP Fatal error: require_once(): Failed opening required '/home/reagand/dev/ldap_wrangler/inc/ldapwrangler/Net_LDAP2.class.php' (include_path='.:/usr/share/php:/usr/share/pear') in /home/reagand/dev/ldap_wrangler/config.php on line 18

FYI, line 18 is the require_once() part of the autoload function.

How to I tell php to not use the ldapwrangler namespace for the Net_LDAP2 classes? Or any other non-ldapwrangler classes, for that matter.

1

There are 1 answers

1
alganet On BEST ANSWER

Declare you're using an external namespace:

<?php

namespace ldapwrangler;
use Net_LDAP2;
require_once 'Net/LDAP2.php';

Every class outside the declared namespace needs to be declared by the use keyword.

Please also take a look at PSR-0, a standard for these kind of things like namespace usage.