第三方视图CodeIgniter 3中的路径检查



我正试图根据加载的第三方路径检查视图文件是否真的存在

通常,我会检查是否存在带有is_file(APPPATH.'/views/folder/'.$view)的视图

我可以用get_package_path检索每个加载的第三方路径(感谢Tpojka的评论),然后在他们的文件夹视图中检查文件是否存在,

但我希望进行"直接"检查,就好像->view函数会返回false,而不是重定向到错误页面一样

$html = $this->load->view($tpl,'',TRUE) ? $this->load->view($tpl,'',TRUE) : $another_template;

尽管我意识到可能没有其他解决方案可以将此手动检查添加到加载路径的循环中,并将其隐藏在CI_Load类扩展(application/core/MY_Loader)中,以在控制器中提供直接检查的外观:

编辑:这是个坏主意,因为view()可能会将false返回到可能不是为设计的CI函数

class MY_Loader extends CI_Lodaer{
public function __construct() {
parent::__construct();
}
public function view($view, $vars = array(), $return = FALSE)
{
foreach( $this->get_package_paths( TRUE ) as $path )
{
// this will only retrieve html from the first file found
if( is_file( $path."/views/".$view ) ) return parent::view($view, $vars, $return);
}
// if no match
return false;
}
}

我觉得烦人的是load->view已经通过路径进行了检查,所以这个解决方案将添加第二次检查并增加服务器消耗。。

最后我选择了这个微温的解决方案:

我只是在application/core/MY_Loader.php 中创建了一个函数is_view(),而不是扩展函数view()使其返回false(然后必须通过CI处理!)

我不确定MY_Loader是放置这样一个函数的正确位置,但到目前为止,它对我来说已经成功了。。。

(thx Tpojka表示)

在application/core/MY_Loader.php 中

/**
* is_view
*
* Check if a view exists or not through the loaded paths
*
* @param   string          $view           The relative path of the file
*
* @return  string|bool     string          containing the path if file exists
*                          false           if file is not found
*/
public function is_view($view)
{
// ! BEWARE $path contains a beginning trailing slash !
foreach( $this->get_package_paths( TRUE ) as $path )
{
// set path, check if extension 'php' 
// (would be better using the constant/var defined for file extension of course)
$path_file = ( strpos($view,'.php') === false ) ?  $path."views/".$view.'.php' : $path."views/".$view ;
// this will return the path at first match found
if( is_file( $path_file ) ) return $path."views/";
}
// if no match
return false;
}

以及应用程序/控制器/Wellome.php

$view = "frames/my_html.php";
/*
*   the view file should be in 
*   application/third_party/myapp/views/frames/my_html.php
*   
*   so far, if the file does not exists, and we try 
*   $this->load->view($view) will redirect to an error page
*/
// check if view exists and retrieve path
if($possible_path = $this->load->is_view($view)) 
{
//set the data array
$data = array("view_path"=>$possible_path);
// load the view knowing it exists
$this->load->view($view,$data)
}
else echo "No Template for this frame in any Paths !";

当然在看来

<h1>My Frame</h1>
<p>
The path of this file is <=?$view_path?>
</p>