利用composer搭建PHP框架(四.数据库与缓存)

本节介绍框架加入数据库与缓存。

数据库是mysql,使用Laravel的数据库ORM类 illuminate/database。

缓存是redis,使用predis。

修改D:\WAMP\wamp\www\framework\composer.json,内容:

{
	"require":{
		"twig/twig": "2.4.4",
		"slim/slim": "3.9.0",
		"illuminate/database": "*",
		"predis/predis": "*"
	}
}

在命令行输入 composer update安装。

修改D:\WAMP\wamp\www\framework\frame\App.php,加载数据库配置和缓存配置,内容:

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Illuminate\Database\Capsule\Manager as Capsule;
use frame\Redis;

// 载入composer自动加载
require ROOT_PATH . '/vendor/autoload.php';

class App {

	public static function run() {
		// 启用 slim路由
		$configuration = [
		    'settings' => [
		        'displayErrorDetails' => true, // 开启错误信息
		    ],
		];
		$c = new \Slim\Container($configuration);
		$app = new \Slim\App($c);
		$app->get('/', function (Request $request, Response $response, array $args) {
			echo 'route err.';
		});

		$app->get('/{platform}/{controller}/{method}', function (Request $request, Response $response, array $args) {
			// 加载平台路由下的配置文件
			self::loadConfigFile(ROOT_PATH . '/app/' . $args['platform']);

			// 加载数据库配置
			self::loadDbConfig();

			// 加载redis
			self::loadRedisConfig();

			// 新建控制器类 调用控制器方法
			$class_name = "{$args['platform']}\\controller\\{$args['controller']}";
			$class = new $class_name;
			$class->{$args['method']}();
		});
		$app->run();
	}

	public static function loadRedisConfig() {
		Redis::init(C('', true, '__redis'));
	}

	public static function loadDbConfig() {
		$capsule = new Capsule;
		// 创建链接
		$capsule->addConnection(C('', true, '__database'));
		// 设置全局静态可访问
		$capsule->setAsGlobal();
		// 启动Eloquent
		$capsule->bootEloquent();
	}

	public static function loadConfigFile($path) {
		if(!is_dir($path)) return ;
		$dh = opendir($path);
		if($dh == false) return ;
		while (($file = readdir($dh)) != false) {
			if($file != '.' && $file != '..') {
				$file_path = $path . '/' . $file;
				if(is_file($file_path)) {
					$file_content = require $file_path;
					if(is_array($file_content)) { // 加载配置文件
						$config_key = '__' . str_replace('.php', '', $file);
						$GLOBALS[$config_key] = $file_content;
					}
				}
			}
		}
		closedir($dh);
	}


}
控制器使用数据库和缓存,修改D:\WAMP\wamp\www\framework\app\index\controller\index.php,内容:

<?php
namespace index\controller;

use frame\View;
use index\model as Model;
use frame\Redis;

class index {

	protected $view;

	public function __construct() {
		$this->view = new View(C('app_name'));
	}

	public function testView() {
		$this->view->assign('name', 'welson');
		$this->view->assign(array('data' => array('tom', 'cat', 'dog')));
		$this->view->display('index/test');
	}

	public function testSql() {
		$user = new Model\User;
		$list = $user->getUserListByNickname('test');
		var_dump($list);
	}

	public function testRedis() {
		Redis::set('name', 'test_name', 300);
		echo Redis::get('name');
	}

}
上面使用了model类,在D:\WAMP\wamp\www\framework\app\index\model\下创建model类User.php,内容:

<?php
namespace index\model;

use Illuminate\Database\Eloquent\Model as Eloquent;

class User extends Eloquent{

	protected $table = 'user';
	protected $primaryKey = 'nouseid';

	/*
	 * 根据昵称查询用户列表
	 */
	public function getUserListByNickname($nickname) {
		return self::where('nick_name', $nickname)
			->orderBy('nouseid', 'desc')
			->offset(1)
			->take(2)
			->get()
			->toArray();
	}

}

使用的缓存类Redis封装了predis的使用,在D:\WAMP\wamp\www\framework\frame\下创建Redis.php,内容:

<?php
namespace frame;

use Predis\Client;

class Redis {

	protected static $redis;
	protected static $config;

	public static function init($config) {
		if(empty(self::$config)) {
			self::$config = $config;
		}
	}

	public static function getRedis() {
		if(empty(self::$redis)) {
			self::$redis = new Client(self::$config);
		}
		return self::$redis;
	}

	public static function set($key, $value, $expire = null) {
		$redis = self::getRedis();
		$res = $redis->set($key, $value);
		if($res && !empty($expire)) {
			$res = $redis->expire($key, $expire);
		}
		return $res;
	}

	public static function get($key) {
		$redis = self::getRedis();
		return $redis->get($key);
	}

}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值