ebr
ebr

Reputation: 37

How to autoload a custom class in Zend Framework 2?

I'm using zend framework2 skeleton, and I'm trying to add my own classes behind vendor folder. The problem is: I don't know how to prepare the classes to be loaded on demand (autoloaded) only when I'll instantiate one of them from any module.

I tried with the solution explained at: How to load a custom library in Zend Framework 2? , but I'm getting the same error:

Fatal error: Class 'myNamespace\myClass' not found in path\IndexController.php on line x

My question is: Where and how should I insert my own classes to be later used from my modules?

Upvotes: 0

Views: 1269

Answers (2)

dixromos98
dixromos98

Reputation: 754

I know its a bit old but i was facing the same issue so what i did was:

inside vendor folder i created a new folder and gave it the name of Custom. Inside that folder i added my class file (MyClass.php).

inside MyClass.php i added this line (namespace Zend\Custom;).

And inside my Controller at the top use Zend\Custom\MyClass;

and within a method of that controller

$someVar = new MyClass();

$someVar->someClassMethod();

I hope this helps.

Upvotes: 0

Tomdarkness
Tomdarkness

Reputation: 3820

Firstly, if they are your own classes and directly related to the modules (i.e not some custom library you have written) then you are better off having them in the actual module, not in the vendor folder.

However, if you are trying to include your own library that you have written I'd suggest you consider storing this elsewhere and adding it as a dependancy via composer.

I don't recommend this but you should be able to get the autoloading working by using the psr0 autoloader built in to composer (assuming your classes follow psr0). Example composer.json config:

{
    [...]
    "autoload": {
        "psr-0": {
            "MyNameSpace": "path/to/root/src/directory"
        }
    }
    [...]
}

Upvotes: 1

Related Questions