我已经创建了我的代码,因为ZF2推动你去做,现在我开始认为它实际上与首先使用命名空间的整点/好处相反。
我想改变一切,但我害怕这样做只是因为ZF不是这样做的,所以我觉得我必须错过一件重要的事情。
我的文件夹/文件结构是这样的:
- Application
- Controller
IndexController.php
- Model
- Table
User.php
Building.php
- Mapper
User.php
Building.php
- Entity
User.php
Building.php
所以在我的控制器中,代码可能看起来像这样,因为ZF2建议你开始:
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController,
Zend\View\Model\ViewModel;
use Application\Model\Entity\User as UserEntity,
Application\Model\Mapper\User as UserMapper,
Application\Model\Table\User as UserTable;
class IndexController extends AbstractActionController {
public function indexAction() {
$userEntity = new UserEntity;
$userMapper = new UserMapper;
$userTable = new UserTable;
就在那里,我只提供了一些项目,但随着应用程序的增长,你最终会得到一个巨大的使用声明,看起来它应该更像下面这样做:
namespace Application;
use Zend\Mvc\Controller\AbstractActionController,
Zend\View\Model\ViewModel;
use Model;
class IndexController extends AbstractActionController {
public function indexAction() {
$userEntity = new Entity\User;
$userMapper = new Mapper\User;
$userTable = new Table\User;
我猜这是因为ZF2正在推动具有大量模块的基于模块的项目。但是,如果需要,我当然可以放入该模块的命名空间?我仍然需要使用当前使用的更合格的名称。
答案 0 :(得分:7)
use
语句是导入命名空间以及如何&导入时,没有编码标准。
您必须记住两件事:
顺便说一下,有一个use
PSR-2指南规定,每次使用时,使用语句必须以;
结尾。所以不是这样:
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController,
Zend\View\Model\ViewModel;
use Application\Model\Entity\User as UserEntity,
Application\Model\Mapper\User as UserMapper,
Application\Model\Table\User as UserTable;
class IndexController extends AbstractActionController {
public function indexAction() {
$userEntity = new UserEntity;
$userMapper = new UserMapper;
$userTable = new UserTable;
}
}
但是这个:
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Model\Entity\User as UserEntity;
use Application\Model\Mapper\User as UserMapper;
use Application\Model\Table\User as UserTable;
class IndexController extends AbstractActionController {
public function indexAction() {
$userEntity = new UserEntity;
$userMapper = new UserMapper;
$userTable = new UserTable;
}
}
所以你可以对此进行清理:
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Model;
class IndexController extends AbstractActionController {
public function indexAction() {
$userEntity = new Model\Entity\User;
$userMapper = new Model\Mapper\User;
$userTable = new Model\Table\User;
}
}
如果您想使用自己的实体和映射器,但是使用来自不同模块的表,代码将被重构为:
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Model;
use OtherModule\Model\Table\User as UserTable;
class IndexController extends AbstractActionController {
public function indexAction() {
$userEntity = new Model\Entity\User;
$userMapper = new Model\Mapper\User;
$userTable = new UserTable;
}
}