Daniel
Daniel

Reputation: 667

Zend Framework 1 - dynamically loading model outside of module

I'm developing a Zend Framework 1.12 based API and have implemented versioning by using modules (v1, v2), with each module being a different version of the API, though this may not be the best practice.

I've got the following directory structure:

application
    modules
        v1
            controllers
            models
        v2
            controllers
            models
library
    Myapp
        controller
            plugin
                TranslateHandler.php
    Zend
public

I have a custom made plugin Myapp_Controller_Plugin_TranslateHandler.php that's called in Bootstrap in order to set the default language or the preferred language if user is authenticated.

Here's my code within TranslateHandler to find a user:

$users = new V1_Model_UsersMapper();
$users->findByAuthToken($auth_token, $usersModel = new V1_Model_Users());

Problem is that I have a model for each module called V1_Model_Users and V2_Model_Users.

I am able to check which module is set via the Request object. I can do something like the following:

$module = $frontController->getRequest()->getModuleName();
if($module == 'v1')
{
    //use V1_Model_Users
}
elseif($module == 'v2')
{
    //use V2_Model_Users
}

However, I want to avoid hard-coding module names within code. Ideally, I would like to load *_Model_Users dynamically within my TranslateHandler plugin.

tl;dr Is there a way to load classes dynamically outside of modules by knowing the module name?

Thanks,

Upvotes: 1

Views: 174

Answers (1)

doydoy44
doydoy44

Reputation: 5772

You can try sometrhing like this:

$module = $frontController->getRequest()->getModuleName();
$module_class = ucfirst($module) . "_Model_Users";
$usersModel  = new $module_class();

Upvotes: 1

Related Questions