Software Engineering

ZF2: Autoloading custom classes without namespaces and without using Composer

Let’s say we have a custom class (for example an external library) that we want to use in a Zend 2 application, but it has no namespace and we also do not want to use Composer. Here’s one way to do it.

Here’s our custom class, which is located in /<module>/libs/MyClass.php.

class MyClass {
	// all kind of interesting stuff happens here...
}

In Module.php add a ClassMapAutoloader to the getAutoloaderConfig function. The StandardAutoloader is used to load the other classes of the module.

public function getAutoloaderConfig() {
	return array(
		'Zend\Loader\ClassMapAutoloader' => array(
			__DIR__ . '/autoload_classmap.php',
		),
		'Zend\Loader\StandardAutoloader' => array(
			'namespaces' => array(
				__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
			),
		),
	);
}

The autoload_classmap.php is created at the same level als Module.php and looks like this:

return array(
	'MyClass'         => __DIR__ . '/libs/MyClass.php',
);
Previous Post Next Post

You Might Also Like

No Comments

Leave a Reply