Get Module Name from Model File


(Anisrehan) #1

I have a unique problem here.
I want to dynamically create Autocomplete Url for a lot of models.
At runtime I don’t know what Model class is being called beside one thing that it is a sub class of ActiveRecord.

I want to create a method in base ActiveRecord class which can create the Url based on model.

The problem arises when
some of the models are at the outermost layer of application.
some are in modules
and further some are in nested modules.

What I want to do is to check whether a particular model class is from module and create the standardized URL using the //autolist format.

The usual help about controller and module
$controller = Yii::app()->controller;
$module = $controller->module;

does not works for me because my request Url will be
application/setting/prefences?user_id=1
Here the controller is always SettingController and no module is called.
However I want to get Autolist of following models.

application/models/Language application/models/Currency application/modules/accounts/models/Accounts application/modules/accounts/products/models/Product

Another way round is to have getAutocompleteUrl function in each of the above models which returns static urls… But that’s too cumbersome and also restricts future models to have such a function.

any help if appreciated.


(Anisrehan) #2

so far I reached this point.

but there is a catch, this does not catch nested module

`public function getAutoCompleteUrl($scope = ‘’) {
$modelClass = get_class($this);

    $reflectionClass = new ReflectionClass($modelClass);
    $fileName = $reflectionClass->getFileName();

    $regexPattern = '/protected\W?(modules)?\W?(\w+)?\Wmodels\W(\w+)/';
    $matches = array();
    preg_match($regexPattern, $fileName, $matches);
    // $matches[0] = full string
    // $matches[1] = modules text
    // $matches[2] = Module Name
    // $matches[3] = Model Class

    $controller = strtolower($modelClass[0]) . substr($modelClass, 1);
    $module = '';
    if (key_exists(2, $matches) && $matches[2]) {
        $module = \Yii::app()->getModule($matches[2]);
    }
    $parentModule = ($module ? ( $module->getParentModule() ? $module->getParentModule()->id : $module->id) : '');
    $url = \Yii::app()->createUrl(($parentModule ? '/' . $parentModule : '') . ($module && $parentModule !== $module->id ? '/' . $module->id : '') . '/' . $controller . '/autolist', array($scope));
    return $url;
}`