Third_party Views Path(s)Check in CodeIgniter 3

时间:2016-06-05 20:27:05

标签: php codeigniter codeigniter-3

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

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

我可以使用get_package_paths检索每个已加载的third_party路径(感谢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->视图已经检查了路径,因此这个解决方案会添加第二次检查并增加服务器消耗。

1 个答案:

答案 0 :(得分:0)

最后我选择了这个不冷不热的解决方案:

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

我不确定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;
}

并在application / controllers / Welcome.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>