DonCallisto
DonCallisto

Reputation: 29912

require_once() and autoloader - How to load flat php?

I have a file (an xmlrpc library for PHP) that I would like to use into a Symfony2 class (so inside a Symfony2 project).

I can't use autoloader because as written here

which is able [the autoloader] to load classes from files that implement one of the following conventions:

1) The technical interoperability standards for PHP 5.3 namespaces and 
   class names;
2) The PEAR naming convention for classes.

If your classes and the third-party libraries you use for your project follow these standards, the Symfony2 autoloader is the only autoloader you will ever need.

the class that I'll go to use, didn't satisfies one of those requirements.

So if I can't autoload that file, since isn't possible (as I understand, but I can go wrong) to use require_once (or simply require) with namespace, what is the solution for this issue?

Upvotes: 2

Views: 2570

Answers (1)

Florent
Florent

Reputation: 12420

Assuming you have a file named xmlrpc.lib.php with the following content:

<?php 
class XMLRPC_Server {
    // ...
}

class XMLRPC_Request {
    // ...
}

class XMLRPC_Response {
    // ...
}

You can create an instance of MapClassLoader to handle it's autoloading:

// Create map autoloader
$mapLoader = new MapClassLoader(array(
    'XMLRPC_Server' => __DIR__.'/../library/xmlrpc.lib.php',
    'XMLRPC_Request' => __DIR__.'/../library/xmlrpc.lib.php',
    'XMLRPC_Response' => __DIR__.'/../library/xmlrpc.lib.php',
));

// Register autoloader
$mapLoader->register();

When one of these classes will be auto-loaded, others will be auto-loaded too because they share the same PHP file.

Upvotes: 5

Related Questions