grayphp / micro
PHP 微型框架。
Requires
- ext-mbstring: *
- ext-openssl: *
- nesbot/carbon: ^2.62.1
- phpmailer/phpmailer: ^6.6
- psr/simple-cache: ^1.0|^2.0|^3.0
- simple-crud/simple-crud: ^7.5
- vlucas/phpdotenv: ^5.5
Requires (Dev)
- filp/whoops: ^2.14
- phpunit/phpunit: ^9.5.8
README
使用Micro - PHP微型框架,实现大思维,小代码,打造Web应用程序。
安装
通过composer安装
composer create-project grayphp/micro my-app
cd my-app
php dev start
https://:4000
用法/示例
可用路由
[get,post,patch,put,delete,any]
路由
use system\router\Route; Route::get('/path',[controller::class,'method']); Route::method('/path',callback);
中间件
Route::any('/profile', ['controller' => HomeController::class, 'profile', 'middleware' => UserAuth::class]);
动态路由
Route::get('/user/$id',function($id)){ print $id; }
控制器
创建控制器
php dev -c MyController
中间件
创建中间件
php dev -m MyMiddleware
数据库
您可以使用DB()助手访问数据库。
基本CRUD
您可以直接与表交互,插入/更新/删除/选择数据
使用ArrayAccess
接口通过id
访问数据
DB实例
$db = DB();
//Get the post id = 3; $post = $db->post[3]; //Check if a row exists if (isset($db->post[3])) { echo 'exists'; } //Delete a post unset($db->post[3]); //Update a post $db->post[3] = [ 'title' => 'Hello world' ]; //Insert a new post $db->post[] = [ 'title' => 'Hello world 2' ]; //Tables implements the Countable interface $totalPost = count($db->post);
按其他字段选择
如果您想通过除id
之外的其他键选择行,只需使用get
方法即可
$post = $db->post->get(['slug' => 'post-slug']);
选择或创建
有时,您可能希望获取一行或如果不存在则创建它。您可以使用getOrCreate
方法轻松完成此操作
$post = $db->post->getOrCreate(['slug' => 'post-slug']);
行
一个Row
对象代表一行数据库,用于读取和修改其数据
//get a row by id $post = $db->post[34]; //Get/modify fields values echo $post->title; $post->title = 'New title'; //Update the row into database $post->save(); //Remove the row in the database $post->delete(); //Create a new row $newPost = $db->post->create(['title' => 'The title']); //Insert the row in the database $newPost->save();
查询
一个Query
对象代表一个数据库查询。SimpleCrud使用魔法方法创建查询。例如,$db->post->select()
在post
表中返回一个新的Select
查询实例。其他示例:$db->comment->update()
、$db->category->delete()
等。每个查询都有如orderBy()
、limit()
等修改器
//Create an UPDATE query with the table post $updateQuery = $db->post->update(['title' => 'New title']); //Add conditions, limit, etc $updateQuery ->where('id = ', 23) ->limit(1); //get the query as string echo $updateQuery; //UPDATE `post` ... //execute the query and returns a PDOStatement with the result $PDOStatement = $updateQuery();
get()
方法执行查询并返回查询的处理结果。例如,使用insert()
返回新行的id
//insert a new post $id = $db->post ->insert([ 'title' => 'My first post', 'text' => 'This is the text of the post' ]) ->get(); //Delete a post $db->post ->delete() ->where('id = ', 23) ->get(); //Count all posts $total = $db->post ->selectAggregate('COUNT') ->get(); //note: this is the same like count($db->post) //Sum the ids of all posts $total = $db->post ->selectAggregate('SUM', 'id') ->get();
select()->get()
返回一个包含结果的RowCollection
实例
$posts = $db->post ->select() ->where('id > ', 10) ->orderBy('id ASC') ->limit(100) ->get(); foreach ($posts as $post) { echo $post->title; }
如果您只需要第一行,请使用修饰符one()
$post = $db->post ->select() ->one() ->where('id = ', 23) ->get(); echo $post->title;
select()
有一些有趣的修饰符,如relatedWith()
,可以自动添加所需的WHERE
子句以选择与其他行或行集合相关的数据
//Get the post id = 23 $post = $db->post[23]; //Select the category related with this post $category = $db->category ->select() ->relatedWith($post) ->one() ->get();
查询API
查询使用Atlas.Query库构建最终查询,因此您可以看到所有可用选项的文档。
选择/选择聚合
更新
插入
删除
延迟加载
两者Row
和RowCollection
都可以自动加载其他相关行。只需使用名为相关表的属性即可。例如
//Get the category id=34 $category = $db->category[34]; //Load the posts of this category $posts = $category->post; //This is equivalent to: $posts = $db->post ->select() ->relatedWith($category) ->get(); //But the result is cached so the database query is executed only the first time $posts = $category->post;
这允许您进行如下操作
$titles = $db->post[34]->tag->post->title; //Get the post id=34 //Get the tags of the post //Then the posts related with these tags //And finally, the titles of all these posts
使用魔法方法获取返回相关行的Select
查询
$category = $db->category[34]; //Magic property: Returns all posts of this category: $posts = $category->post; //Magic method: Returns the query instead the result $posts = $category->post() ->where('pubdate > ', date('Y-m-d')) ->limit(10) ->get();
解决n+1问题
可以通过以下方式解决n+1选择问题
//Get some posts $posts = $db->post ->select() ->get(); //preload all categories $posts->category; //now you can iterate with the posts foreach ($posts as $post) { echo $post->category; }
您可以自行执行选择以包括修饰符
//Get some posts $posts = $db->post ->select() ->get(); //Select the categories but ordered alphabetically descendent $categories = $posts->category() ->orderBy('name DESC') ->get(); //Save the result in the cache and link the categories with each post $posts->link($categories); //now you can iterate with the posts foreach ($posts as $post) { echo $post->category; }
对于多对多关系,您需要执行一个额外的步骤
//Get some posts $posts = $db->post ->select() ->get(); //Select the post_tag relations $tagRelations = $posts->post_tag()->get(); //And now the tags of these relations $tags = $tagRelations->tag() ->orderBy('name DESC') ->get(); //Link the tags with posts using the relations $posts->link($tags, $tagRelations); //now you can iterate with the posts foreach ($posts as $post) { echo $post->tag; }
关联和解关联数据
要保存相关行到数据库,您需要这样做
//Get a comment $comment = $db->comment[5]; //Get a post $post = $db->post[34]; //Relate $post->relate($comment); //Unrelate $post->unrelate($comment); //Unrelate all comments of the post $post->unrelateAll($db->comment);
分页
查询有一个特殊的修饰符用于分页结果
$query = $db->post->select() ->page(1) ->perPage(50); $posts = $query->get(); //To get the page info: $pagination = $query->getPageInfo(); echo $pagination['totalRows']; //125 echo $pagination['totalPages']; //3 echo $pagination['currentPage']; //1 echo $pagination['previousPage']; //NULL echo $pagination['nextPage']; //2