搜索
首页php教程php手册200行描述MVC,读完kohana总结的一点笔记

200行大点,读完kohana总结的一点笔记。 无 ?php header('Content-type: text/html; charset=utf-8'); define('__ROOT__',str_replace('\\','/', __DIR__ )); //set_exception_handler(array("Factory","last_fun")); 设置一个用户定义的异常处理函数 Factory

200行大点,读完kohana总结的一点笔记。
<?php
    header(&#39;Content-type: text/html; charset=utf-8&#39;);
        
    define(&#39;__ROOT__&#39;,str_replace(&#39;\\&#39;,&#39;/&#39;, __DIR__ ));
    //set_exception_handler(array("Factory","last_fun")); 设置一个用户定义的异常处理函数  
    Factory::getIns($_SERVER[&#39;REQUEST_URI&#39;]);
    abstract class ProductInterface
    {
        public $data=array();  //用于接收传过来的内容 
        public static $magic_quotes =NULL;
        public function __construct()
        {
            self::$magic_quotes = (version_compare(PHP_VERSION, &#39;5.4&#39;) < 0 AND get_magic_quotes_gpc());
            // 清洁所有请求变量
            $_GET    = self::sanitize($_GET);
            $_POST   = self::sanitize($_POST);
            $_COOKIE = self::sanitize($_COOKIE);
        }
       
        public static function sanitize($value)
        {
            if (is_array($value) OR is_object($value))  {
                foreach ($value as $key => $val)  { 
                    $value[$key] = self::sanitize($val);
                }
            } elseif (is_string($value)) { 
                if (self::$magic_quotes === TRUE) { 
                    $value = stripslashes($value);
                }  
                if (strpos($value, "\r") !== FALSE) {
                    $value = str_replace(array("\r\n", "\r"), "\n", $value);
                }
            } 
            return $value;
        }
        
        public function __set($k,$v)
        {
            $this->$k = $v;
        }
        
        public function __call($method,$arg)
        {
             echo &#39;错误指定页面&#39;;
             print_r($arg); //错误指定页面
        } 
        
        public static function __callStatic($method,$arg)
        {
             print_r($arg);  //错误指定页面 静态的好像不太可能 先写这儿了
        }
        
        public function assign($key,$value)
        {
            $this->data[$key] = $value;
        }
        
        //引入模板
        public function display($template,$ext = &#39;.html&#39;)
        {
            $template_path = $template.$ext;
            if(file_exists($template_path)){
              foreach ($this->data as $k=>$v){
                $this->__set($k,$v);
              }
               include $template_path;
            }
        }
    }
  
  
  
//控制器
    class IndexAction extends ProductInterface
    {
        public function index()
        { 
            print_r( $_GET); 
           //$body = file_get_contents(&#39;php://input&#39;); 
           //print_r($body);  //结果为  member_id=1234567    enctype="multipart/form-data"
          // print_r($_POST); //结果为  Array ( [member_id] => 1234567 )  
           

		   //$model= new Article(&#39;article&#39;);
           // $arr= $model->select(&#39;SELECT * FROM article limit 2&#39;);
         
		 //print_r($arr);
        }
            
        public function admin($array)
        {
           $model= new Article(&#39;article&#39;); 
           $array=array();
           $array[&#39;rec&#39;]=&#39;admins&#39;;
           $array[&#39;pos&#39;]=&#39;李斯&#39;;
           $array[&#39;content&#39;]=&#39;hellow world&#39;; 
           echo  $model->add($array);
        }
    } 
    
///控制器2
    class AdminAction extends ProductInterface
    {
        public function index($array)
        { 
          echo __method__.&#39;方法&#39;;
        }
    }
  
  
    class Factory
    {
        protected static $ins=null; 
        protected  function __construct(){
           ob_start(); //打开缓冲区  
           static::autoLoad();  
           register_shutdown_function(array(&#39;Factory&#39;,&#39;last&#39;)); //程序执行完后执行 
        }
        
        public static function getIns($url){
            if(self::$ins instanceof self ){
               self::$ins->execute($url); 
           }else{
              self::$ins = new self();
              self::$ins->execute($url); 
           } 
        }
 
        protected function set_router($uri) {
/* 
        $uri=&#39;index/admin&#39;;  
       // $route_regex=&#39;#^(?:(?P[^/.,;?\n]++)(?:/(?P[^/.,;?\n]++)(?:/(?P[^/.,;?\n]++))?)?)?$#uD&#39;;
         //$route_regex=&#39;#^captcha(?:/(?P[^/.,;?\n]++))?$#uD&#39;;  
        $route_regex=&#39;#^(?:(?P<controller>[^/.,;?\n]++)(?:/(?P<action>[^/.,;?\n]++)(?:/(?P<id>[^/.,;?\n]++))?)?)?$#uD&#39;;
        if ( ! preg_match($route_regex, $uri, $matches)) {
            echo &#39;没有匹配上&#39;;
        } else {
            print_r($matches);
        }
*/
              $arr=array();   
              if (strpos($uri,&#39;?&#39;) === false) {
                   $pathinfo=array();
                   
                   if (!empty($_SERVER[&#39;PATH_INFO&#39;])) {
                      $arg=trim($_SERVER[&#39;PATH_INFO&#39;],&#39;/&#39;);
                   } else if ($request_uri = parse_url($_SERVER[&#39;REQUEST_URI&#39;], PHP_URL_PATH)){
                      //有效的URL路径发现,设置它。 
                      $arg= trim($request_uri,&#39;/&#39;); 
                   } 
                  if(stripos($arg,&#39;/&#39;) !== false) {
                     $pathinfo=explode(&#39;/&#39;,$arg);
                  }
                  $arr[&#39;ctrolloer&#39;]= isset($pathinfo[0])? $pathinfo[0] : &#39;index&#39; ;
                  array_shift($pathinfo);
                  $arr[&#39;action&#39;]= isset($pathinfo[0])?$pathinfo[0]:&#39;index&#39; ;
                  array_shift($pathinfo);
                  $num=count($pathinfo);
                  for ($i=0;$i<$num;$i+=2) {
                     $arr[&#39;param&#39;][$pathinfo[$i]]=$pathinfo[$i+1];
                  }
                 
                  return $arr; 
            } else {
                   $ln=parse_url($uri); 
                   parse_str($ln[&#39;query&#39;],$array);
                   $arr[&#39;ctrolloer&#39;]=$array[&#39;m&#39;] ? strtolower($array[&#39;m&#39;]) : &#39;index&#39;;
                   $arr[&#39;action&#39;]=$array[&#39;c&#39;] ? strtolower($array[&#39;c&#39;]) : &#39;index&#39;;
                   unset($array[&#39;m&#39;]); unset($array[&#39;c&#39;]);
                   $arr[&#39;param&#39;]=$array; 
                   return $arr;
            }
        }
 
        protected function execute($url)
        {
            $arr= self::$ins->set_router($url);
            $_GET =  isset($arr[&#39;param&#39;]) ? $arr[&#39;param&#39;] : array();
            $ProductType = ucfirst($arr[&#39;ctrolloer&#39;]).&#39;Action&#39;; 
            if (class_exists($ProductType)) {
              $p=new $ProductType();
              $p->$arr[&#39;action&#39;]($arr);
            } else {
                throw new Exception("Error Processing Request", 1);
            }
        }
        
        public static function last()// echo  &#39;脚本执行完了&#39;. PHP_EOL;
        {  
            $info=ob_get_contents(); //得到缓冲区的内容并且赋值给$info
            $file=fopen($_SERVER[&#39;DOCUMENT_ROOT&#39;].DIRECTORY_SEPARATOR.&#39;indexs.html&#39;,&#39;w&#39;); ///打开文件 指定缓存目录 
            fwrite($file,$info); //写入信息到info.txt  
            fclose($file); //关闭文件info.txt   
            //ob_end_clean();
            ob_end_flush();
            flush(); 
        }
        
         static  public function loadFile($className)
         {
                $dir=array(); 
                $dir[0]=__ROOT__.&#39;/application/&#39;;    //指定多个目录
                $dir[1]=__ROOT__.&#39;/module/&#39;;
                $file_arr=self::find_file($dir,$className);
                foreach($file_arr as $value){
                    if(is_file($value) ){
                        return include_once $value;
                     }else{
                        throw new \Exception(&#39;找不到&#39;.$className.&#39;类&#39;);
                     }
                }
          }

           public static function find_file($paths=array(),$name)
           {
                $name=ucfirst($name).&#39;.php&#39;;
                $found=array();
                foreach ($paths as $dir){
                   if (is_file($dir.$name)){
                     $found[] = $dir.$name;
                   }
                }
               return $found;    
           }
             
            // 注册自动装载机
            static public function autoLoad()
            {
                spl_autoload_register( array(__CLASS__,&#39;loadFile&#39;) );
            }
        
            // 注册自动装载机2   //如有必要注册多个自动加载函数
            static public function autoLoad2()   
            {
                spl_autoload_register( array(__CLASS__,&#39;loadFile2&#39;) );
            }
    }
     
    
    
    abstract class DB{
            public $db=NULL;
            public $table=NULL;
            public $config=array(
                           &#39;dsn&#39;=>&#39;mysql:dbname=test;host=127.0.0.1&#39;,
                           &#39;user&#39;=>&#39;root&#39;,
                           &#39;password&#39;=>&#39;root&#39;,
						   &#39;charset&#39;=>&#39;utf8&#39;,
						   &#39;persistent&#39;=>false  //持久性链接
                           );
          
			public  $options = array(
				PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES ",
			);
			
			public function __construct($table){
				$this->table=$table;
				$this->options[PDO::MYSQL_ATTR_INIT_COMMAND] .= $this->config [&#39;charset&#39;];
				if($this->config [&#39;persistent&#39;]){
					$this->options[PDO::ATTR_PERSISTENT] = true;
				} 
				try {
				   // 长连接,如有需要将array(PDO::ATTR_PERSISTENT=>true) 作为第四个参数
				  $this->db=$pdo = new \PDO ( $this->config [&#39;dsn&#39;],$this->config [&#39;user&#39;],$this->config [&#39;password&#39;],$this->options);
				  
				 //$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT); //不显示错误
				 
				  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);//显示警告错误,并继续执行
				  
				  $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//产生致命错误,PDOException
				  //$this->db->exec(&#39;set names utf8&#39;);
				 } catch ( \Exception $e ) {
					throw new \Exception ( $e->getMessage () );
				 }
			}
	 
            public function query($sql){
               return  $re=$this->db->query($sql);
            }
       
            public function select($sql) /*查询*/  
            {
                $re=$this->query($sql);
                return $re->fetchAll();
            }  

            public function add($arr=array()){  /*添加*/
                $sql = &#39;insert into &#39; . $this->table . &#39; (&#39; . implode(&#39;,&#39;,array_keys($arr)) . &#39;)&#39;;
                $sql .= " values (&#39;";
                $sql .= implode("&#39;,&#39;",array_values($arr));
                $sql .= "&#39;)"; 
                $stmt = $this->db->prepare($sql);
                $stmt->execute($arr); 
               echo $this->db->lastinsertid();   
           } 
           
           public function update($arr,$where = &#39; where 1 limit 1&#39;){ /*修改*/
            //$sql = "UPDATE `user` SET `password`=:password WHERE `user_id`=:userId";   
            $sql = &#39;update &#39; . $this->table .&#39; set &#39;;
            foreach($arr as $k=>$v) {
                $sql .= $k . "=&#39;" . $v ."&#39;,";
            }
             $sql = rtrim($sql,&#39;,&#39;);
             $sql .= $where; 
               $stmt = $this->db->prepare($sql);
             $stmt->execute($arr);    
               return $stmt->rowCount();        
           }
           
           public function delete($sql){ /*删除*/ 
             $stmt = $this->db->prepare($sql);
             $stmt->execute();
             return $stmt->rowCount();
           } 
    }
    ////可以每一张表一个类 统一继承DB类。。。。。
    class Article extends DB{ 
    }
?>  
<script>
    var x=1,y=z=0;
    function add(n){
      n=n+1;
    }
    y=add(x);
    function add(n){
      n=n+3;
    }
z=add(x); 
</script>
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境