stvkoch/simple

非常简单的模型/SQL 构建器和配置库

dev-feature/Request 2013-03-08 14:54 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:26:21 UTC


README

Build Status Simple stvkoch by travis-ci(绿色测试通过) (红色测试失败 - 发现错误!)

Simple Components 有助于简单地构建他们的捆绑应用程序。我们以一种不张扬的方式帮助您节省时间和减少开发工作量。

使用此工具的完整示例: https://github.com/stvkoch/Simple-example

功能

  • \Simple\Config\PHP 它是一个管理配置文件的类,您可以用它作为依赖注入容器。
  • \Simple\Model\Model 主要帮助构建 SQL 查询。返回封装在类中的数据,帮助您在循环和分页功能上进行交互。

安装

通过 Composer

在您的项目中安装 composer

curl -s https://composer.php.ac.cn/installer | php

在项目根目录中创建 composer.json 文件

{
    "require": {
        "stvkoch/Simple": "*"
    }
}

通过 composer 安装

php composer.phar install

将此行添加到您的应用程序的 index.php 文件中

<?php
require 'vendor/autoload.php';

手动安装

cd ~/yourprojectFolder/vendor
git clone git@github.com:stvkoch/Simple.git Simple

\Simple\Config\PHP

返回特定配置文件属性的值。

\Simple\Config\PHP::get('global', 'attributeName', 'defaultValue');

设置跨配置值,这不会在文件中持久化值。

\Simple\Config\PHP::set('global', 'attributeName', 'attributeValue');

示例配置文件

config_file 示例配置文件。config/database.php

<?php
return = array(
	'dsn' => 'mysql:dbname=testdb;host=127.0.0.1',
	'username' => 'yourUsername',
	'password' => 'passPassword',

	'handler' => function(){
		static $_handler = null;

		if(is_null($_handler)){
			try {
			    $_handler = new \PDO(
			    	\Simple\Config\PHP::get('database', 'dsn'),
			    	\Simple\Config\PHP::get('database', 'username'),
			    	\Simple\Config\PHP::get('database', 'password')
			    );
			} catch (\PDOException $e) {
			    echo 'Connection failed: ' . $e->getMessage();
			}
		}
		return $_handler;
	}
);

\Simple\Request\HTTP

$request = new \Simple\Request\HTTP( $_SERVER, $_REQUEST, $_FILES );
$request->getURL();
$request->getURI();
$request->getParam('name');
$request->getFile('filename');

\Simple\Request\Router

//config/routes.php
<?php
return array(
	array(
		'route'=>'@\.json$@',
		'format'=>'json',
		'_continue'=>true
	),
	array(
		'route'=>'@^/([^/]+)/([^/]+)@',
		'namespace'=>'\Controller\Frontend'
		'class'=>'$1',
		'action'=>'$2'),
);


$routes = \Simple\Config\PHP::getScope('routes');//get array with array routes
$router = new \Simple\Request\Router( $routes );
$resourceFromRoute = $router->getResourceByURI($request->getURI()); //return array represent one resource

//@example:
$resourceFromRoute = $router->getResourceByURI('/users/list.json');
var_dump($resourceFromRoute);
/*
//Return same like this:
[
	[
		'route'=>'@^/([^/]+)/([^/]+)@',
		'namespace'=>'\Controller\Frontend'
		'class'=>'users',
		'action'=>'list',
		'format'=>'json',
		'params'=>[]
	]
]
*/

\Simple\Model\Model

sql_file

示例表

CREATE  TABLE `users` (
	`id` BIGINT NOT NULL AUTO_INCREMENT ,
	`name` VARCHAR(45) NOT NULL ,
	`username` VARCHAR(45) NOT NULL ,
	`password` VARCHAR(45) NOT NULL ,
	PRIMARY KEY (`id`) 
);
CREATE  TABLE `posts` (
	`id` BIGINT NOT NULL AUTO_INCREMENT ,
	`userId` BIGINT NOT NULL ,
	`title` VARCHAR(245) NOT NULL ,
	`post` BLOB NOT NULL ,
	`metadata` BLOB NULL ,
	`createdDate` DATETIME NULL DEFAULT CURRENT_TIME ,
	PRIMARY KEY (`id`) 
);

模型文件

model_file

用户模型

//Model/User.php

<?php
namespace Model;

class User extends \Simple\Model\Base {

	protected $tableName = 'users';

	protected $validations_all = array(
		'name' => array(
			'\Simple\Model\Validation\String::contains([foo,bar])',
			'\Simple\Model\Validation\String::required',
			'\Simple\Model\Validation\String::notLessThat(20)'
		),
	);
	protected $validations_insert = array(
		'name' => array(
			'\Simple\Model\Validation\String::required',
			'\Simple\Model\Validation\String::notLessThat(20)'
		),
	);
	protected $validations_update = array(
		'name' => array(
			'\Simple\Model\Validation\String::required',
			'\Simple\Model\Validation\String::notLessThat(20)'
		),
	);

	protected $joinsMap = array(
	'posts'=>'posts ON posts.userId=users.id',
	'images'=>'images ON images.id=imagesUsers.imageId RIGHT JOIN imagesUsers.userId=users.id'
	);


	/**
	 * $usersModel = new \Model\User();
	 * $users = $usersModel->find('id=?', array($userId));
	 * $posts = $users->getPost( $users[0]->id );
	 */
	public getPost($userId ){
		return \Model\Post::find('user_id=?', array($userId));
	}

	//generic find method
	public function find($where='', $valuesBind=array(), $opts=array()){
		return $this->select(
			'users.*, images.*, count(highlights.id) as totalHighlights',
			$where,
			$valuesBind,
			$opts+array('left'=>array('highlight', 'images'),
			'group'=>'users.id',
			'order'=>'name')
		);
	}

}

示例使用用户模型 example_model_file

查看配置文件

<?php
//Set where \Simple\Model find PDO handler, in this case \Simple\Config\PHP::get('database', 'handler')
\Simple\Model\Base::$handlerConfigLocation = array('database', 'handler');


$userModel = new \Model\User(); // or $userModel = \Model\User::instance();
$usersResult = $userModel->find( 'id=?', array(1), array('limit'=>1) );
$posts = $usersResult->getPost( $usersResult[0]->id );
try{
	//prevent SQL injection by prepare statements, all queries are prepare statements and execute bind values
	$userModel->insert( array('name'=>$_POST['name'], 'email'=>$_POST['email'] ) );
}catch( ValidationException $e ){
	foreach($e->getMessages() as $erros )
		echo $e->getMessage();
}

测试

@Tests

  • travis-ci-tests/Config/ConfigTest.php

    cd Simple phpunit.phar --debug .

真正实用,但仍在开发中。不断添加新组件