icon-attention デザイン新しくしました。

icon-calendar 2019年4月14日

【PHP】自作MVC用のdispatcher晒す

未分類

といってもPHP7がまだでてない高校3年のときに書いたものなのであしからず

<?php
class Dispatcher
{
    // setされたものはここに入っていきます。デバッグの際はこいつをvar_dumpなりしよう。
    private $var = array();
    function __construct () {}
    public function __get($key)
    {
        return $this->get($key);
    }
    public function __set($key, $value)
    {
        $this->set($key, $value);
    }
    public function get($key, $default = null)
    {
        if (array_key_exists($key, $this->var)) {
            return $this->var[$key];
        } else {
            return $default;
        }
    }
    public function set($key, $value)
    {
        $this->var[$key] = $value;
    }
    // ここまでSetterGetterのプログラム。自動でしてくれます。

    public function dispatch()
    {
        $this->uri = get('REQUEST_URI', 'server', 1);
        
        // ディレクトリをゲットして頭と尾の/を消す
        $uri = $this->uri;
        $uri = preg_replace('{^/*}', '', $uri);
        $uri = preg_replace('{/*$}', '', $uri);
        
        $this->path = explode('/', $uri);
        
        $path = $this->path;
        
        // 以下振り分けの本プログラム。ucfirst()は頭の文字だけを大文字にする関数。
        if (!empty($path[0])) {
            if (!empty($path[1])) {
                if (file_exists(CONTROLLER . ucfirst($path[0]) . ucfirst($path[1]) . '.php')) {
                    include(CONTROLLER . ucfirst($path[0]) . ucfirst($path[1]) . '.php');
                } else {
                    header('location: /');
                    exit;
                }
            } else {
                if (file_exists(CONTROLLER . ucfirst($path[0]) . 'Index.php')) {
                    include(CONTROLLER . ucfirst($path[0]) . 'Index.php');
                } else {
                    header('location: /');
                    exit;
                }
            }
        } else {
            include(CONTROLLER . 'Index.php');
        }
    }
    function __destruct () {}
}