我想在app/Model
下获得所有模型的完整列表。
已经尝试过App::objects('Model')
,但它只检索加载的模型。
这可能在CakePHP 2中吗?
经过一些研究,我发现App::objects('Model')
返回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;
}
也许迟到但这里是我的版本:(循环插件模型,并通过打开文件检索关联的表,并搜索变量$ useTable)
/**
* Get models list.
* Retrieved from: https://stackoverflow.com/questions/38622473/get-models-list-in-cakephp-2
* @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);
}
}
}
}
}