Putting models in library directory in Zend Framew

2019-07-01 10:13发布

I want to put models outside module directory in Zend Framework. To be precise, in /library folder

library/
  models/
    actors/
      ActorsMapper.php
      Actor.php
    books/
      BooksMapper.php
      Book.php

INSTEAD OF

application/
modules/
   models/
    actors/
      ActorsMapper.php
      Actor.php
    books/
      BooksMapper.php
      Book.php

This is done so that I don't have to create separate model for each of the module I create. What configurations will I have to change? If you need more details, please ask.

Thank you :)

3条回答
来,给爷笑一个
2楼-- · 2019-07-01 10:42

If you want to use same models for all modules you can put it in application folder applications/models

and that works fine just like when you have web without modules.

But If you want to have models in library, You can put 'models' folder in your library path and autoload it.

  1. Create folder 'Models' into library with all Table.php files.
  2. In configs/application.ini Put:

    autoloaderNamespaces.models = "Models_"
    

Then you can use namespace 'Models_' in your web application

In controller:

    $model = new Models_Table();

in any case, I recommend that you keep the folder models in the path application/models

查看更多
\"骚年 ilove
3楼-- · 2019-07-01 10:45

First answer works, but I will give you another answer in case if you want to register autoload in bootstrap.

1) put 'models' folder into library with all Table.php files.

Every model/class should have:

class Model_Table extends Zend_Db_Table_Abstract{ ... }

2) In bootstrap.php put:

protected function _initAutoLoad() {
    // Add autoloader empty namespace
    $autoLoader = Zend_Loader_Autoloader::getInstance();
    $resourceLoader = new Zend_Loader_Autoloader_Resource(
            array(
                'basePath'      => APPLICATION_PATH,
                'namespace'     => '',
                'resourceTypes' => array(
                'model'         => array(
                        'path'      => '../library/models/',
                        'namespace' => 'Model_'
                    ),
                ),
            )
    );
    return $resourceLoader;
}

That's it. Now you can use your models in controllers like this:

$model = new Model_Table();
查看更多
再贱就再见
4楼-- · 2019-07-01 11:03

zend autoloader loading class which name beginning with prefix, that is registred on it. If you have library in your include path, you can simple register "Models" like default namespace on autoloader and name your class for example Models_Actors_Actor.

查看更多
登录 后发表回答