转载

使用composer构建PHP框架之引入数据库ORM框架(四)

本文来说一下引入数据库ORM框架的方法,选择的是Laravel 的 illuminate/database

修改composer.json增加一个 require 项:

"illuminate/database": "*"

运行 composer update 完成安装

修改 init.php 为:

<?php  use Illuminate/Database/Capsule/Manager as Capsule;  //定义 BASE_PATH define('BASE_PATH', __DIR__);  // Autoload 自动载入 require BASE_PATH.'/vendor/autoload.php';  //Eloquent ORM $capsule = new Capsule; $capsule->addConnection(require BASE_PATH.'/config/database.php'); $capsule->bootEloquent();

新建config/database.php:

<?php  return array(      'driver'    => 'mysql',     'host'      => 'localhost',     'database'  => 'nuf',     'username'  => 'root',     'password'  => '',     'charset'   => 'utf8',     'collation' => 'utf8_general_ci',     'prefix'    => '' );

修改models/Post.php为:

<?php  class Post extends /Illuminate/Database/Eloquent/Model{  }

修改controllers/HomeController.php为:

<?php  class HomeController extends BaseController{     public function home(){         $rs = Post::all();         $data = $rs->toArray();         echo View::getView()->make('home', array('data'=>$data))->render();     } }

修改views/home.blade.php为:

<!DOCTYPE html> <html> <head>     <meta charset="UTF-8">     <title>home view</title> </head> <body>     @foreach($data as $v)         title:{{ $v['title'] }}<br/>     @endforeach </body> </html>

访问 nuf.dev/index.php/home,输出

title:php title:java

本文使用sql及数据如下:

CREATE DATABASE IF NOT EXISTS `nuf`; USE `nuf`; CREATE TABLE `posts` (  `id` INT(11) NOT NULL AUTO_INCREMENT,  `title` VARCHAR(50) NOT NULL DEFAULT '0',  `content` VARCHAR(50) NOT NULL DEFAULT '0',  PRIMARY KEY (`id`) ) COLLATE='utf8_general_ci' ENGINE=InnoDB AUTO_INCREMENT=3 ; INSERT INTO `posts` (`id`, `title`, `content`) VALUES  (1, 'php教程', 'php教程内容'),  (2, 'java教程', 'java教程内容');
原文  http://www.36nu.com/post/192.html
正文到此结束
Loading...