duandang6111
2018-05-03 18:51
浏览 51
已采纳

在自制的PHP MVC框架中呈现视图文件

I've developed My Own MVC Framework using php. I call view files in controller like:

include('../view/home.php'); 

but I want to use it like:

$this->view('home');

How can I define common function for that where I can just pass view name i.e home only and it will do include view file without passing the full file path?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongmi4035 2018-05-03 19:02
    已采纳

    No one could answer you without seeing your codes really. But this should be my approach. You should have a class that all your controllers extend. Lets say that you have class Controllers and all your controllers extend it.

    Then you may have a method inside the class named view($view_name).

    public function view($view_name){
       include $some_path . '/' . $view_name . '.php';
    }
    

    then whenever you call view by $this->view it will include the view if it exists. This is not the best approach and I did not test the code. I just wanted to show you the path

    点赞 打赏 评论
  • doudeng5218 2018-05-03 20:31

    I don't know Your MVC file/directory/namespace and etc structure.

    But for beginner who tries to learn MVC and Frameworks by "reinventing wheel" (: I can give such example:

    1) Create common abstract controller class in app/controllers folder:

    namespace App\Controllers;
    
    abstract class Controller {
    
      public function view($name) {
        include(__DIR__.'/../views/'.$name.'.php';
      }
    
    }
    

    2) Create Your own controller i.e. PagesController and use it:

    namespace App\Controllers;
    
    class PagesController extends Controller {
    
      public function home() {
        $this->view('home');
      }
    }
    

    p.s. You may omit namespace-ing, abstract word depending on autoloader logic

    点赞 打赏 评论

相关推荐 更多相似问题