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('Content-type: text/html; charset=utf-8'); define('__ROOT__',str_replace('\\','/', __DIR__ )); //set_exception_handler(array("Factory","last_fun")); 设置一个用户定义的异常处理函数 Factory::getIns($_SERVER['REQUEST_URI']); abstract class ProductInterface { public $data=array(); //用于接收传过来的内容 public static $magic_quotes =NULL; public function __construct() { self::$magic_quotes = (version_compare(PHP_VERSION, '5.4') < 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 '错误指定页面'; 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 = '.html') { $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('php://input'); //print_r($body); //结果为 member_id=1234567 enctype="multipart/form-data" // print_r($_POST); //结果为 Array ( [member_id] => 1234567 ) //$model= new Article('article'); // $arr= $model->select('SELECT * FROM article limit 2'); //print_r($arr); } public function admin($array) { $model= new Article('article'); $array=array(); $array['rec']='admins'; $array['pos']='李斯'; $array['content']='hellow world'; echo $model->add($array); } } ///控制器2 class AdminAction extends ProductInterface { public function index($array) { echo __method__.'方法'; } } class Factory { protected static $ins=null; protected function __construct(){ ob_start(); //打开缓冲区 static::autoLoad(); register_shutdown_function(array('Factory','last')); //程序执行完后执行 } 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='index/admin'; // $route_regex='#^(?:(?P[^/.,;?\n]++)(?:/(?P[^/.,;?\n]++)(?:/(?P[^/.,;?\n]++))?)?)?$#uD'; //$route_regex='#^captcha(?:/(?P[^/.,;?\n]++))?$#uD'; $route_regex='#^(?:(?P<controller>[^/.,;?\n]++)(?:/(?P<action>[^/.,;?\n]++)(?:/(?P<id>[^/.,;?\n]++))?)?)?$#uD'; if ( ! preg_match($route_regex, $uri, $matches)) { echo '没有匹配上'; } else { print_r($matches); } */ $arr=array(); if (strpos($uri,'?') === false) { $pathinfo=array(); if (!empty($_SERVER['PATH_INFO'])) { $arg=trim($_SERVER['PATH_INFO'],'/'); } else if ($request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)){ //有效的URL路径发现,设置它。 $arg= trim($request_uri,'/'); } if(stripos($arg,'/') !== false) { $pathinfo=explode('/',$arg); } $arr['ctrolloer']= isset($pathinfo[0])? $pathinfo[0] : 'index' ; array_shift($pathinfo); $arr['action']= isset($pathinfo[0])?$pathinfo[0]:'index' ; array_shift($pathinfo); $num=count($pathinfo); for ($i=0;$i<$num;$i+=2) { $arr['param'][$pathinfo[$i]]=$pathinfo[$i+1]; } return $arr; } else { $ln=parse_url($uri); parse_str($ln['query'],$array); $arr['ctrolloer']=$array['m'] ? strtolower($array['m']) : 'index'; $arr['action']=$array['c'] ? strtolower($array['c']) : 'index'; unset($array['m']); unset($array['c']); $arr['param']=$array; return $arr; } } protected function execute($url) { $arr= self::$ins->set_router($url); $_GET = isset($arr['param']) ? $arr['param'] : array(); $ProductType = ucfirst($arr['ctrolloer']).'Action'; if (class_exists($ProductType)) { $p=new $ProductType(); $p->$arr['action']($arr); } else { throw new Exception("Error Processing Request", 1); } } public static function last()// echo '脚本执行完了'. PHP_EOL; { $info=ob_get_contents(); //得到缓冲区的内容并且赋值给$info $file=fopen($_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'indexs.html','w'); ///打开文件 指定缓存目录 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__.'/application/'; //指定多个目录 $dir[1]=__ROOT__.'/module/'; $file_arr=self::find_file($dir,$className); foreach($file_arr as $value){ if(is_file($value) ){ return include_once $value; }else{ throw new \Exception('找不到'.$className.'类'); } } } public static function find_file($paths=array(),$name) { $name=ucfirst($name).'.php'; $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__,'loadFile') ); } // 注册自动装载机2 //如有必要注册多个自动加载函数 static public function autoLoad2() { spl_autoload_register( array(__CLASS__,'loadFile2') ); } } abstract class DB{ public $db=NULL; public $table=NULL; public $config=array( 'dsn'=>'mysql:dbname=test;host=127.0.0.1', 'user'=>'root', 'password'=>'root', 'charset'=>'utf8', 'persistent'=>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 ['charset']; if($this->config ['persistent']){ $this->options[PDO::ATTR_PERSISTENT] = true; } try { // 长连接,如有需要将array(PDO::ATTR_PERSISTENT=>true) 作为第四个参数 $this->db=$pdo = new \PDO ( $this->config ['dsn'],$this->config ['user'],$this->config ['password'],$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('set names utf8'); } 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 = 'insert into ' . $this->table . ' (' . implode(',',array_keys($arr)) . ')'; $sql .= " values ('"; $sql .= implode("','",array_values($arr)); $sql .= "')"; $stmt = $this->db->prepare($sql); $stmt->execute($arr); echo $this->db->lastinsertid(); } public function update($arr,$where = ' where 1 limit 1'){ /*修改*/ //$sql = "UPDATE `user` SET `password`=:password WHERE `user_id`=:userId"; $sql = 'update ' . $this->table .' set '; foreach($arr as $k=>$v) { $sql .= $k . "='" . $v ."',"; } $sql = rtrim($sql,','); $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>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Introduction In today's rapidly evolving digital world, it is crucial to build robust, flexible and maintainable WEB applications. The PHPmvc architecture provides an ideal solution to achieve this goal. MVC (Model-View-Controller) is a widely used design pattern that separates various aspects of an application into independent components. The foundation of MVC architecture The core principle of MVC architecture is separation of concerns: Model: encapsulates the data and business logic of the application. View: Responsible for presenting data and handling user interaction. Controller: Coordinates the interaction between models and views, manages user requests and business logic. PHPMVC Architecture The phpMVC architecture follows the traditional MVC pattern, but also introduces language-specific features. The following is PHPMVC

The MVC architecture (Model-View-Controller) is one of the most popular patterns in PHP development because it provides a clear structure for organizing code and simplifying the development of WEB applications. While basic MVC principles are sufficient for most web applications, it has some limitations for applications that need to handle complex data or implement advanced functionality. Separating the model layer Separating the model layer is a common technique in advanced MVC architecture. It involves breaking down a model class into smaller subclasses, each focusing on a specific functionality. For example, for an e-commerce application, you might break down the main model class into an order model, a product model, and a customer model. This separation helps improve code maintainability and reusability. Use dependency injection

The MVC (Model-View-Controller) pattern is a commonly used software design pattern that can help developers better organize and manage code. The MVC pattern divides the application into three parts: Model, View and Controller, each part has its own role and responsibilities. In this article, we will discuss how to implement the MVC pattern using PHP. Model A model represents an application's data and data processing. usually,

SpringMVC framework decrypted: Why is it so popular, specific code examples are needed Introduction: In today's software development field, the SpringMVC framework has become a very popular choice among developers. It is a Web framework based on the MVC architecture pattern, providing a flexible, lightweight, and efficient development method. This article will delve into the charm of the SpringMVC framework and demonstrate its power through specific code examples. 1. Advantages of SpringMVC framework Flexible configuration method Spr

In Web development, MVC (Model-View-Controller) is a commonly used architectural pattern for processing and managing an application's data, user interface, and control logic. As a popular web development language, PHP can also use the MVC architecture to design and build web applications. This article will introduce how to use MVC architecture to design projects in PHP, and explain its advantages and precautions. What is MVCMVC is a software architecture pattern commonly used in web applications. MV

Developing MVC with PHP8 framework: Important concepts and techniques that beginners need to know Introduction: With the rapid development of the Internet, Web development plays an important role in today's software development industry. PHP is widely used for web development, and there are many mature frameworks that help developers build applications more efficiently. Among them, the MVC (Model-View-Controller) architecture is one of the most common and widely used patterns. This article will introduce how beginners can use the PHP8 framework to develop MVC applications.

Developing MVC with PHP8 Framework: A Step-by-Step Guide Introduction: MVC (Model-View-Controller) is a commonly used software architecture pattern that is used to separate the logic, data and user interface of an application. It provides a structure that separates the application into three distinct components for better management and maintenance of the code. In this article, we will explore how to use the PHP8 framework to develop an application that conforms to the MVC pattern. Step One: Understand the MVC Pattern Before starting to develop an MVC application, I

Beego is a web application framework based on Go language, which has the advantages of high performance, simplicity and ease of use, and high scalability. Among them, the MVC architecture is one of the core design concepts of the Beego framework. It can help developers better manage and organize code, improve development efficiency and code quality. This article will delve into Beego's MVC architecture so that developers can better understand and use the Beego framework. 1. Introduction to MVC architecture MVC, or Model-View-Controller, is a common
