Access another Module's Model

Hello,

I am trying to access a module’s model from within a controller in the root / protected directory.

E.g:

protected/controllers/AController.php:




$log = new ProductCategory;



The ProductCategory model sits in protected/modules/sales/models.

I am getting the error


include(ProductCategory.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory

Thanks in advance + regards,

Joachim

Welcome to the forum!

You have to import the modules model folder in the config.




...

'import' => array(

   ...

   'application.modules.sales.models.*',

   ...

),

...



You can also make your model available in said controller by Yii::app()->getModule(‘moduleName’);

i.e

Yii::app()->getModule(‘sales’); in your case.

why not calling all models from the protected/models folder?

But that method only returns the module instance, he can not access a model with that?

Yes he will be able to. Have a go at it and see.

I don’t understand. When the model path of the model he want to access is nowhere defined (through import in config), how can the application itself access it?

Can you explain more or give example? I just tried it and didn’t worked.

Thanks!

either importing from config or Yii::app()->getModule worked.

Regards,

Joachim

Eg:

I have a module in my application called ‘account’. My LoginForm model is under protected/modules/account/models. My login action is in SiteController located under protected/cotrollers with the action ‘login’ i.e actionLogin()…

The login action requires LoginForm from protected/modules/account/models.

I get it by doing this:




Yii::app()->getModule('account');

$LoginForm = new LoginForm;



When you generate a module with yiic, the web module will import the models and components of that module in the init method by default as shown here.




	public function init()

	{

		// this method is called when the module is being created

		// you may place code here to customize the module or the application


		// import the module-level models and components

		$this->setImport(array(

			'account.models.*',

			'account.components.*',

		));

	}



example attached.

I see, that makes sense now - I didn’t used yiic yet :)

Thanks for the long explanation!