在 CakePHP 2 中获取模型列表

Get models list in CakePHP 2

我正在尝试获取 app/Model 下所有模型的完整列表。

已经尝试过 App::objects('Model') 但它只检索加载的模型。

这在 CakePHP 2 中可行吗?

经过一番研究,我发现 App::objects('Model') returns app/Models 下的所有模型,但不包括插件模型。

为了包含所有模型(应用程序模型和插件模型),我创建了下一个函数:

/**
 * Get models list
 *
 * @return array
 */
public static function getModels()
{
    // Get app models
    $models = App::objects('Model');

    $models = array_combine($models, $models);

    // Get plugins models
    $pluginsFolder = new Folder(APP . 'Plugin');

    $plugins = $pluginsFolder->read();

    foreach ( $plugins[0] as $plugin ) {

        $pluginModels = App::objects($plugin . '.Model');

        foreach ($pluginModels as $pluginModel) {

            $models[$plugin . '.' . $pluginModel] = $plugin . '.' . $pluginModel;

        }

    }

    // Exclude tableless and application models
    $dataSource = ConnectionManager::getDataSource('default');

    $sources = $dataSource->listSources();

    foreach($models as $key => $model) {

        $table = Inflector::tableize(self::modelName($key));

        if (stripos($model, 'AppModel') > -1 || !in_array($table, $sources)) {

            unset($models[$key]);

        }

    }

    return $models;
}

可能晚了,但这是我的版本: (遍历插件模型,并通过打开文件检索关联的 table,并搜索变量 $useTable

/**
 * Get models list.
 * Retrieved from: 
 * @return array
*/
public static function getModels() {

    // Get app models
    $models = App::objects('Model');
    $models = array_combine($models, $models);

    // Get plugins models
    $pluginsFolder = new Folder(APP . 'Plugin');
    $plugins = $pluginsFolder->read();

    foreach ( $plugins[0] as $plugin ) {
        $pluginModels = App::objects($plugin . '.Model');
        foreach ($pluginModels as $pluginModel) {
            $fullPath = APP.'Plugin'.DS.$plugin.DS."Model".DS.$pluginModel.".php";
            $models[$plugin . '.' . $pluginModel] = $fullPath;
        }
    }

    foreach($models as $model => $modelPath) {
        if(file_exists($modelPath)) {
            $data = file_get_contents($modelPath);

            $find = array();
            $find[] = "useTable = '";
            $find[] = "useTable='";
            $find[] = "useTable= '";
            $find[] = "useTable ='";

            foreach($find as $condition) {
                $pos = strrpos($data, $condition);
                if($pos !== false ) {
                    $pos+=(strlen($condition));

                    $tableName = substr($data, $pos, (strpos($data, "';", $pos)-$pos));
                    debug($tableName);
                }    
            }
        }

    }
}

CakePHP v2

在 AppController 中

if (in_array('YOUR_MODEL', $this->uses)) {
    //found
}