Search code examples
php.htaccessmodel-view-controllerdatacontext

Php MVC Model - why the context (path) changes in the same controller/view when default home parameter is replaced by the same in: url[1]


I would like to adopt in my php project the MVC model. I have created the folder structure: models, views, controllers, etc...

The problem I am facing:

if I navigate to: "www.mysite.com/home" (note that the 'index' method gets called by default), the site loads resources (/css, /img, etc..) just fine.

BUT, if I call: "www.mysite.com/home/index" (same as the default value), my resources fails to load (ie: it looks for css in: home/index/css, which does not exist)...:(

I have rewrote rules inside .htaccess, so things should be included in my /index.php right? Than why the path changes to my resources?

Steps I do in my app:

In my core App.php declare:

protected $controller = 'home';
protected $method = 'index';
protected $params = [];

by default these pages are open via:

public function __construct(){
      $url = $this->parseUrl();

      if(file_exists('app/controllers/' . $url[0] . '.php')){
          $this->controller = $url[0];
          unset($url[0]); //remove it from the array
      }

      require_once 'app/controllers/' . $this->controller . '.php';
      $this->controller = new $this->controller;


      if(isset($url[1])){
        if(method_exists($this->controller, $url[1])){
          $this->method = $url[1];
          unset($url[1]);
        }
      }


      $this->params = $url ? array_values($url) : [];
      call_user_func_array([$this->controller, $this->method], $this->params);
    }


    public function parseUrl(){
      if(isset($_GET['url'])){
          return $url = explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
      }
    }

Than the contoller home.php gets called witch fetches the right index.php file by extending the core Controller:

class Home extends Controller {

    public function index($name = ''){

      //$user = $this->model('User');
      //$user->name = $name;

      $this->view('home/index', []);
    }

}

Controller.php

class Controller {

  public function model($model){
    require_once 'app/models/' . $model . '.php';
    return new $model();
  }


  public function view($view, $data = []){
    require_once 'app/views/' . $view . '.php';
  }

.htaccess:

Options -MultiViews
RewriteEngine On

RewriteBase /home/prbh0pr/public_html/

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

folder structure: enter image description here


Solution

  • if you are in controller you need css/js file that e.g if you are in yourweb.com/public/home

    <script type="text/javascript" src="js/md/tinymce.min.js"></script>
    

    if home/index

     <script type="text/javascript" src="../js/md/tinymce.min.js"></script>