2

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
  • 1
    Why not have a variable $this->viewPath and then in the function just concatenate the viewPath with the value passed to the view function? See: stackoverflow.com/a/50162193/3578036 Commented May 3, 2018 at 19:01
  • That's not a view. It's a template. Views are classes, that contain the presentation logic. Commented May 4, 2018 at 7:10

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.