PHP code example of pfinal / leaf
1. Go to this page and download the library: Download pfinal/leaf library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
pfinal / leaf example snippets
use Leaf\Route;
Route::get('/', function(){
return 'Hello Leafphp!';
});
Route::post('foo', function(){
return 'post only';
});
Route::any('bar', function(){
return 'any';
});
Route::get('user/:id', function($id){
return 'user id: ' . $id;
});
use Leaf\Request;
Route::any('foo', function(Request $request){
$name = $request->get('name');
return $name; // leaf
});
Leaf\Request
Leaf\Application
use Leaf\Url;
$url = Url::to('foo'); /demo/web/foo
$url = Url::to('foo', ['id' => 1]); /demo/web/foo?id=1
$url = Url::to('foo', true); http://localhost/demo/web/foo
use Leaf\Request;
Route::any('test', function (Request $request) {
//GET POST PUT DELETE HEAD ...
$method = $request->getMethod();
$bool = $request->isMethod('post') // post request
$bool = $request->isXmlHttpRequest() // ajax request
$id = $request->get('id'); // $_POST['id'] or $_GET['id']
$arr = $request->all(); // $_POST + $_GET
});
use Leaf\View;
use Leaf\Response;
use Leaf\Json;
Route::any('/', function(){
//string
return 'Hello Leaf!';
return new Response('Hello Leaf!');
//view
return View::render('home.twig'); // 输出views/home.twig模板中内容
//json
return Json::render(['status' => true, 'data' => 'SUCCESS']);
return Json::renderWithTrue('SUCCESS');
return Json::renderWithTrue('ERROR');
});
use Leaf\Redirect;
return Redirect::to('foo'); // 跳转到 Url::to('foo')
return Redirect::to('/'); // 项目的根目录
return Redirect::to('http://www.example.com'); // 外部链接
namespace Middleware;
use Leaf\Request;
class TestMiddleware
{
public function handle(Request $request, \Closure $next)
{
$id = $request->get('age');
if ($id < 18) {
return 'age error';
}
return $next($request);
}
}
$app['test'] = 'Middleware\TestMiddleware';
use Leaf\Request;
Route::any('info', function (Request $request) {
return $request->get('age');
}, 'test');
use Leaf\Request;
Route::group(['middleware' => 'test'], function () {
Route::any('info', function (Request $request) {
return $request->get('age');
});
//other route
});
use Leaf\Request;
public function handle(Request $request, \Closure $next)
{
$response = $next($request);
// your code ...
return $response;
}
namespace Controller;
class SiteController
{
public function home()
{
return 'Hello Leafphp!';
}
}
Route::get('home','Controller\SiteController@home');
// src/Controller/UserController.php
/**
* @Middleware auth
*/
class UserController
{
/**
* @Route user/info
* @Method get
*/
public function info()
{
// your code ...
}
}
use Leaf\View;
// views/index.twig
return View::render('home.twig', [
'name' => 'Leaf',
]);
// views/index.blade.php
return View::render('home', [
'name' => 'Leaf',
]);
\Leaf\View::share('url', 'http://example.com');
$app->extend('twig', function ($twig, $app) {
/** @var $twig \Twig_Environment */
$twig->addFunction(new \Twig_SimpleFunction('count', function ($arr) use ($app) {
return count($arr);
}));
return $twig;
});
src/
FooBundle/ Bundle总目录
FooBundle.php Bundle类文件
Controller/ 控制器
resources/ 资源目录
routes.php 路由文件
views/ 视图目录
// src/FooBundle/FooBundle.php
class FooBundle extends \Leaf\Bundle
{
}
$app->registerBundle(new \FooBundle\FooBundle());
return View::render('@FooBundle/home.twig');
php console make:bundle
$conn = DB::getConnection();
$conn->execute() // 执行SQL(INSERT、UPDATE、DELETE)
$conn->query() // 执行SQL(SELECT)
$conn->queryScalar() // 执行SQL,查询单一的值(SELECT COUNT)
$conn->getLastInsertId() // 返回自增id
$conn->beginTransaction() // 开启事务
$conn->commit() // 提交事务
$conn->rollBack() // 回滚事务
$conn->getLastSql() // 最近执行的SQL
$query = DB::table()
// DBQuery返回数据的方法:
$query->findOne()
$query->findByPk()
$query->findOneBySql()
$query->findAll()
$query->findAllBySql()
$query->count()
$query->paginate($pageSize)
//DBQuery连惯操作方法,返回DBQuery对象:
$query->where()
$query->whereIn()
$query->limit()
$query->offset()
$query->orderBy()
$query->asEntity()
$query->lockForUpdate()
$query->lockInShareMode()
//分块操作
$query->chunk()
$query->chunkById()
$query = DB::select('user')->where($condition, $params);
$page = new Pagination();
$queryCount = clone $query;
$page->itemCount = $queryCount->count();
$query->limit($page->limit)->findAll();
use Leaf\Session;
//设置Session
Session::set('username', 'Jack');
//获取Session
$username = Session::get('username');
//删除Session
Session::remove('username');
//获取Session,如果不存在,使用`guest`作为默认值
$username = Session::get('username', 'guest');
//设置闪存数据
Session::setFlash('message', 'success');
//是否有闪存数据
$bool = Session::hasFlash('message');
//获取闪存数据,闪存数据获取后将自动删除
$message = Session::getFlash('message');
$data = [
'username' => 'jack',
'email' => '[email protected] ',
'age' => '18',
'info' => 'abc',
];
$rules = [
[['username', 'email'], 'mpare', 'type' => 'number', 'operator' => '>=', 'compareValue' => 0],
[['age'], 'compare', 'type' => 'number', 'operator' => '<=', 'compareValue' => 150],
];
$labels = [
'username' => '用户名',
];
if (!Validator::validate($data, $rules, $labels)) {
var_dump(Validator::getFirstError());
var_dump(Validator::getErrors());
}
use Leaf\Exception\HttpException;
throw new HttpException(400, '您访问的页面不存在');
throw new HttpException(500, '服务器内部错误');
use Leaf\Log;
Log::debug("日志内容");
Log::info("日志内容");
Log::warning("日志内容");
Log::error("日志内容");
//注册
$app->register(new \Leaf\Provider\CaptchaProvider());
//生成验证码图片
\Leaf\Route::get('captcha', function (\Leaf\Application $app) {
return $app['captcha']->create();
});
//表单中使用验证码
\Leaf\Route::any('show', function () {
$html = <<<TAG
<form method="post" action="{{ url('validate') }}">
<img src="{{ url('captcha') }}" onclick="this.src='{{ url('captcha') }}?refresh='+Math.random()" style="cursor:pointer" alt="captcha">
<input name="code">
<button type="submit">提交</button>
</form>
TAG;
return View::renderText($html);
});
//提交表单时验证输入是否正确
\Leaf\Route::post('validate', function (\Leaf\Application $app, \Leaf\Request $request) {
if ($app['captcha']->validate($request->get('code'))) {
// 'success';
} else {
// 'Verification code is invalid.';
}
});
// 显示指定内容验证码图片
$obj = new \Leaf\Provider\CaptchaProvider();
return $obj->create('1234');
use Leaf\UploadedFile;
$up = new UploadedFile($config);
if ($up->doUpload($name)) {
//上传后的文件信息
$file = $up->getFile();
}
use Service\Auth
Auth::onceUsingId($userId);
Auth::loginUsingId($userId);
Auth::getUser()
Auth::getId()
$app->register(new \Leaf\Auth\GateProvider(), ['gate.config' => ['authClass' => 'Service\Auth']]);
$app['gate'] = $app->extend('gate', function ($gate, $app) {
/** @var $app \Leaf\Application */
/** @var $gate \Leaf\Auth\Gate */
//用户是否有执行某个task的权限
$gate->define('task', function (\Entity\User $user, $taskCode) {
// 判断权限
if (xxx){
return true;
}else{
return false;
}
});
return $gate;
});
// 判断是否有权限
$bool = Auth::user()->can('task', $taskCode);
$app['Leaf\Pagination'] = function () {
$page = new \Leaf\Pagination();
$page->pageSize = 15;
$page->prevPageLabel = '<span class="glyphicon glyphicon-chevron-left"></span>';
$page->nextPageLabel = '<span class="glyphicon glyphicon-chevron-right"></span>';
return $page;
};
` 标签开始,不写PHP结束标记: `