Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Sep 2012
    Posts
    76
    Thanks
    61
    Thanked 0 Times in 0 Posts

    spl_autoload_register help?

    Hello, I have a class that uses the reflection class that Fou-Lu kindly helped me with to load storage drivers like so

    PHP Code:

    //Include all the files that might be needed
    include_once 'mysql.class.php';
    include_once 
    'pdo.class.php';
    include_once 
    'xml.class.php';
    //etc

    class Connection {
     public static function 
    createConnection($type) {
       
    $driver $type 'Driver';
       if (!
    class_exists($driver)) {
         throw new 
    Exception('No drivers for storage type: ' $type);
       }
       
    $ref = new ReflectionClass($driver);
       return 
    $ref->getMethod('Connection')->invoke(NULL);
       }

    But rather than including ALL the drivers that I might need before I access my class I wanted to make use the spl_autoload_register feature to load the drivers as and when they are needed.

    Is this possible with the above, as I don't get how to do it? As it would be trying to use the spl_autoload_register to load the ReflectionClass each time, as it loads the class name rather than the $type passed in I would have thought?

    Is there a way around this? Or any type of other solution?

    Thank You

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Yeah, you can use an autoload to do this. But since your class files don't match your class names, you'll need to strip the 'Driver' name off of it in order to find it.

    PHP Code:
    function driverLoader($sDriver)
    {
        if (!
    class_exists($sDriver))
        {
            
    $sClass str_ireplace('Driver'''$sDriver);
            require_once 
    $sClass '.class.php';
        }
    }

    spl_autoload_register('driverLoader'); 

  • Users who have thanked Fou-Lu for this post:

    Oatley (11-07-2012)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •