简体   繁体   中英

ZF2 namespace and file system

I have standard Application module in ZF2. It's configured by default, I didn't change anything. I just added some stuff:

module/
  Application/
    src/
      Application/
        Entity/
          Product/
            **Product.php**        
        Controller/
          **IndexController.php**

Product.php

namespace Application\Entity;

class Product
{

}

IndexController.php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Entity\Product;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {       
        $product = new Product();   
    }
}

and I get following error:

Fatal error: Class 'Application\Entity\Product' not found in \module\Application\src\Application\Controller\IndexController.php on line 20

I use the same namespace, but it doesn't see it. Why?

PS: If I will change Product.php to be the following:

namespace Application\Entity\Product;

class Product
{

}

then in the IndexController.php the following code will be working:

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Entity\Product\Product;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {       
        $product = new Product();   
    }
}

UPDATE I see that I have to follow PSR-0 standard, but can you explain a bit, does this standard come from php core OR it's just a funcitonality implemented in ZF2 framework? Also can I change this behaviour? I'm not saying it's good, I just want to know how it actually works! For example I want to use Application\\Entity\\Product and Product class is located in /Application/Entity/Product/Product.php. Thank you in advance!

If you put class Product in namespace Application\\Entity then your directory structure should be

module/
  Application/
    src/
      Application/
        Entity/
          **Product.php**

see also the PSR-0

You should follow PSR-2. So the correct namespace would actually be 'Application\\Entity\\Product' for your current folder structure. And that means you have to do

new \Application\Entity\Product\Product;

or

use Application\Entity\Product\Product;
new Product;

If you only want it to be Application\\Entity\\Product then you should move the file to the folder 'Entity'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM