PHP code example of bobby / api-framework

1. Go to this page and download the library: Download bobby/api-framework 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/ */

    

bobby / api-framework example snippets


//引入初始化脚本并获得框架核心引擎
$app = mponent\Http\Request\InstanceFactory::make();

//根据请求路由寻址并进行一系列处理工作,响应结果
$app->responsePipeline($request);

//引入route组件代理类
use Bobby\Component\Proxy\Route;
use Bobby\Component\Proxy\Request;

//定义get方法请求路由,响应动作可以为闭包执行或控制器方法,此处是闭包*
Route::get('/', function(){
 	echo '<h1 style="position:fixed;left:0;right:0;top:0;bottom:0;margin:auto;width:100%;height:30px;text-align:center;">
	do(9 ^ v ^)9 { Bobby :D\'s frame work started ; } while( 6 _ 6 )
	</h1>';
});

//定义任意方法请求路由,响应动作可以为闭包执行或控制器方法,此处是控制器,以下同理
Route::any('/example/{name}/{id}', 'ExampleController::iocExample')->wrappers(['example', 'before', 'after']);

//定义post方法请求路由
Route::post('/{member}/member', function($member, \StdClass $std) {*
	var_dump(Request::post(), Request::filter('post'), $member, $std);*
});

//路由组定义,路由组即同组的路由会享有共同的配置,路由组可嵌套
Route::group(['wrappers' => ['before', 'example']], function($route) {

	$route->group(['wrappers' => 'after'], function($route) {

		$route->get('/home', function(){

			//事件监听系统
			\Bobby\Component\Proxy\Event::fire(new \App\Event\Example("Event mode example </br>"));

			echo 'This is home .</br>';*
		});

	});
});

Route::get('user/{id}', function ($id) {
	return 'User ' . $id;
});

Route::get('posts/{post}/comments/{comment}', function ($post, $comment) {
	return $post . '-' . $comment;
});

//路由组定义
Route::group(['wrappers' => ['before', 'example']], function($route) {
	//以下两个路由将经过同样的中间件:before和example中间件

	$route->get('/home', function(){
		echo 'This is home .</br>';*
	});
	$route->post('/welcome', function(){
		echo 'Welcome .</br>';*
	});
	
});

namespace App\Controller;

use Bobby\Component\Proxy\Request; //Request组件的门面
use Bobby\Contract\Config\Config; //Config契约

/**
 * 控制器示例代码
 */
class ExampleController
{
	public function iocExample($name, $id, \StdClass $std, $default = 'ioc')
	{
	   	var_dump($name, $id, $std, $default, Request::get());
	}
}

return [
    
    'default' => 'mysql', //默认使用的数据库连接

    //数据库连接列表
    'connections' => [

        'mysql' => [

            'driver' => 'mysql',        //数据库驱动
            'user' => 'root',           //用户名
            'password' => '',           //密码
            'database' => 'test',       //数据库
            'charset' => 'utf8mb4',     //字符集
            'prefix' => '',             //表前缀
            'timeout' => 1,             //连接超时时间,false表示无限制
            'error_mode' => 2,          //0 静默模式,默认的出错了不管;1 警告模式,如果出错了就会报出警告;2 异常模式,如果出错会采用异常来处理(PDOException) 
            'pconnect' => true,         //是否开启长连接

            //读写分离配置
             'read' => [

                [
                    'host' => '127.0.0.2:3306',
                ],
                [
                     'host' => '127.0.0.3:3306',
                     'user' => 'admin',
                     'password' => '123456'
                ]

             ],

             'write' => [
		[
		     'host' => '127.0.0.2:3306',
		],
             ]

        ]

    ]

];

use Bobby\Component\Proxy\DB;

$users = DB::query('select * from users where active = ?', [1]);
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Bobby']);
$affected = DB::update('update users set votes = 100 where name = ?', ['Bobby']);
$deleted = DB::delete('delete from users where id = ?', [1]);

$connector = DB::connectWrite();
DB::query('begin', [], $connector);
#do something
DB::query('commit', [], $connector);

$user = DB::table('user');

DB::table('users')->select();

DB::table('users')->find();

$users = DB::table('users')->count();

$price = DB::table('orders')->max('price');

当然,你可以联合其它查询子句和聚合函数来构建查询:

$price = DB::table('orders')
                ->where('finalized', 1)
                ->average('price');

$users = DB::table('users')->column(['name', 'email as user_email'])->select();

$users = DB::table('users')->columnRaw('name, email as user_email')->select();

$users = DB::table('users')->columnSub(function($query) {
  $query->table('config')->find();
})->select();
//或者
$query = DB::table('config')->find();
DB::table('users')->columnSub($query)->select();

$users = DB::table('users')->distinct()->select();

$users = DB::table('users')->where('votes', '=', 100)->select();

$users = DB::table('users')->where('votes', 100)->select();

$users = DB::table('users')
            ->where('votes', '>=', 100)
            ->select();

$users = DB::table('users')
            ->where('votes', '<>', 100)
            ->find();
	    
$user = DB::table('users')
	    ->where('name', '=', 'john')
	    ->find();
	    
$user = DB::table('users')
	    ->where('name', 'john')
	    ->find();
	    
$users = DB::table('users')
            ->where('name', 'like', 'T%')
	    ->where('status', 1)
            ->select();
	    
//复杂where条件
$user = DB::table('users')
	    ->where(function($query) {
	       $query->where(id, 2)->where('name', 'born');
	    })
	    ->find();

//子查询作为where条件
$users = DB::table('users')
	     ->where('name', 'in', function($query) {
	     	$query->table('orders')->where('goods', 'apple')->column('name');
	     })
	     ->select();
//或者
$query = DB::table('orders')->where('goods', 'apple')->column('name');
$users = DB::table('users')->where('name', 'in', $query)->select();

$users = DB::table('users')->where([
    ['status', '=', '1'],
    ['name', 'john'],
    ['subscribed', '<>', '1', 'or'],
])->select();

$users = DB::table('users')
             ->where('votes', '>', 100)
             ->where('name', '=' ,'John', 'or')
             ->select();

$users = DB::table('users')
             ->where('name', 'in', ['John', 'or'])
             ->select();

$users = DB::table('users')
             ->whereRaw('name in (?, ?)', ['John', 'or'])
             ->select();

$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id', 'LEFT')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->column('users.*', 'contacts.phone', 'orders.price')
            ->find();

//join添加and条件子句
$users = DB::table('users')
            ->join('contacts', function($query) {
		$query->on('orders', 'users.id', '=', 'orders.user_id')
		->and('users.id', '=', 2);
            }, null, null, 'LEFT')
            ->select();

$users = DB::table('users')->groupBy(['sex', 'tall'])->having('age', '=', '18')->select();

$users = DB::table('users')->groupBy(['sex', 'tall'])->having('age', '=', '18')->select();
//或者
$users = DB::table('users')->groupBy(['sex', 'tall'])->having('age', '18')->select();

//可以通过原生sql进行having筛选
$users = DB::table('users')->groupBy(['sex', 'tall'])->havingRaw('age = ?', [18])->select();

DB::table('users')->select()->orderBy('id', 'ASC')->orderBy('score', 'DESC')->select();

//你也可以通过原生sql指定排序方式:
DB::table('users')->select()->orderByRaw('id ASC, score, DESC')->select();

DB::table('users')->offset(5)->limit(10)->select();

$query = DB::table('users')->where('id', 10)->find();
DB::table('users')->union($query)->find();

//union all查询
$query = DB::table('users')->where('id', '<',10)->select();
DB::table('users')->union($query)->find();

DB::table('users')->insert(['name' => 'john', 'sex' => 'man']);
//批量插入
DB::table('users')->insert(
	  [	
	    ['name' => 'john', 'sex' => 'man'],
	    ['name' => 'venis', 'sex' => 'woman']
	   ]
	);

DB::table('users')->where('id', 15)->update(['nickname' => 'rabbit']);

namespace App\Provider;

use Bobby\Component\Provider\WrapperProvider as Provider;

/**
 * 包装器服务提供者
 */
class WrapperProvider extends Provider
{
	public $isDeffer = true;

	protected $wrap = [
		'example' => '\\App\\Wrapper\\Example',
		'before' => '\\App\\Wrapper\\BeforeExample',
		'after' => '\\App\\Wrapper\\AfterExample',
	];

	public $provide = ['example', 'before', 'after'];

}


namespace App\Wrapper;

use Closure;

class BeforeWrapper
{
    public function handle(Closure $next)
    {
        // 执行动作

        return $next($request);
    }
}


namespace App\Wrapper;

use Closure;

class AfterMiddleware
{
    public function handle(Closure $next)
    {
        return $next($request);
	
	// 执行动作
    }
}


namespace App\Http\Middleware;

use Closure;

class CheckRole
{
    /**
     * 处理输入请求
     */
    public function handle(Closure $next, $role, $manager = 'all')
    {
        if ($mamager !== $role) {
            // Redirect...
        }

        return $next($request);
    }

}

Route::any('/example/{name}/{id}', 'ExampleController::iocExample')->wrappers(['example', 'before', 'after']);
Route::group(['wrappers' => ['before', 'example']], function($route) {
	$route->get('/home', function(){			
	});
});

Route::any('/example/{name}/{id}', 'ExampleController::iocExample')->wrappers(['example:admin', 'before:18', 'after:12, john']);//按参数定义顺序传入
 
namespace App\Provider;

use Bobby\Component\Provider\EventProvider as Provider;

/**
 * 事件系统服务提供者
 */
class EventProvider extends Provider
{
	protected $listen = [
		'YourNameSpace\\Example' => 'YourNameSpace\\Example'
	];

	public function register()
	{
		parent::register();
	}

	public function boot()
	{
		parent::boot();
	}
}

namespace App\Event;

/**
 * 事件定义示例代码
 */
class Example
{

	public $data;

	public function __construct($data)
	{
		$this->data = $data;
	}

}

namespace App\Listener;

use App\Event\Example as Event;

/**
 * 事件监听器示例代码
 */
class Example
{

	public function handle(Event $event)
	{
		echo $event->data . '</br>';
	}

}

\Bobby\Component\Proxy\Event::fire(new \App\Event\Example("Event mode example"));

use \Bobby\Component\Proxy\Config;
//获取app\Config\app.php里的'foo'配置
Config::get('app.foo');
//设置默认返回值
Config::get('app.foo', 'bar');
//临时设置app\Config\database里面的connections的mysql的host配置:
Config::set('database.connections.mysql.host', '192.169.2.5');

/**
 * http请求接口类
 */
interface Request
{
    /**
     * [get 获取GET数据]
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public function get($name = null, $defaultValue = null);

    /**
     * [post 获取POST数据]
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public function post($name = null, $defaultValue = null);

    /**
     * [files 获取$_FILES参数]
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public function files($name = null, $defaultValue = null);

    /**
     * [coockie 获取cookie数据]
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public function coockie($name = null, $defaultValue = null);

    /**
     * [server 获取环境变量$_SERVER数据]
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public function server($name = null, $defaultValue = null);

    /**
     * [getPHPInput 获取原始的POST包体]
     * @param  [type] $paramterName [description]
     * @param  [type] $defaultValue [description]
     * @return [type]               [description]
     */
    public function getPHPInput($paramterName = null, $defaultValue = null);

    /**
     * [http 获得所有http请求参数]
     * @return [type] [description]
     */
    public function http();

    /**
     * [header 获得请求头]
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public function header($name = null);

    /**
     * [uri 获得当前请求URI,不包括GET参数]
     * @return [type] [description]
     */
    public function uri();

    /**
     * [uriWithQuery 获得当前请求完整URI,包括GET参数]
     * @return [type] [description]
     */
    public function uriWithQuery();

    /**
     * [method 获得当前请求方法]
     * @return [type] [description]
     */
    public function method();

    /**
     * [time 获得当前请求时间]
     * @return [type] [description]
     */
    public function time();

    /**
     * [setGlobalFilter 设置全局的过滤方法]
     * @param array $callbacks [description]
     */
    public function setGlobalFilter(array $callbacks);

    /**
     * [filter 返回并过滤相应数据]
     * @param  string     $name      [description]
     * @param  array|null $callbacks [description]
     * @param  boolean    $append    [description]
     * @return [type]                [description]
     */
    public function filter(string $name, array $callbacks = null, $append = true);

}

\Bobby\Component\Proxy\Request::get('foo');

\Bobby\Component\Proxy\Request::get('foo','bar');

\Bobby\Component\Proxy\Request::post();
\Bobby\Component\Proxy\Request::cookie();
\Bobby\Component\Proxy\Request::server();

echo \Bobby\Component\Proxy\Request::server('method');

\Bobby\Component\Proxy\Request::uri();

\Bobby\Component\Proxy\Request::filter('post.foo', ['trim', 'htmlspacialchar']); //获得试用trim和htmlspacialchar过滤后的$_POST['foo'],过滤
函数名写入到第二个参数数组中,不添加过滤函数则不做任何处理;

\Bobby\Component\Proxy\Request::setGlobalFilter(['trim', 'strtolower', 'ucfirst']);
\Bobby\Component\Proxy\Request::filter('post.foo'); //自动为$_POST['foo']用trim和strtolower和ucfirst函数过滤
\Bobby\Component\Proxy\Request::filter('get.foo', ['htmlspecialchar']);全局函数和指定函数htmlspecialchar叠加过滤

$app = new \App\Core\Application;

$app->bind('HelpSpot\API', function ($app) {
    return new HelpSpot\API($app->make('HttpClient'));
});

app->singleton('HelpSpot\API', function ($app) {
    return new HelpSpot\API($app->make('HttpClient'));
});

$api = new HelpSpot\API(new HttpClient);
$this->app->instance('HelpSpot\API', $api);

$app->bind(
    'App\Contracts\EventPusher', 
    'App\Services\RedisEventPusher'
);

$api = $app->make('HelpSpot\Api');
$api->json(['username' => 'john']);


namespace App\Provider;

use Riak\Connection;
use Bobby\Contract\Provider\Provider;

class RiakServiceProvider extends Provider{
    /**
     * 在容器中注册绑定.
     *
     * @return void
     */
    public function register()
    {
        $this->container->singleton(Connection::class, function ($app) {
            return new Connection(config('riak'));
        });
    }
}


namespace App\Provider;

use Bobby\Contract\Provider\Provider;

class ComposerServiceProvider extends Provider{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $this->container->make('view')->build('home.html', function () {
            //
        });
    }
}



namespace App\Providers;

use Riak\Connection;
use Illuminate\Support\ServiceProvider;

class RiakServiceProvider extends ServiceProvider{
    /**
     * 服务提供者加是否延迟加载,默认为false
     *
     * @var bool
     */
    protected $isDeffer = true;
    
    /**
      * [$provide 绑定延迟加载的服务名称数组]
      * @var [type]
     */
     public $provide = [Connection::class];

    /**
     * 注册服务提供者
     *
     * @return void
     */
    public function register()
    {
        $this->container->singleton(Connection::class, function ($app) {
            return new Connection($app['config']['riak']);
        });
    }

}


namespace App\Providers;

use Riak\Connection;
use Illuminate\Support\ServiceProvider;

class RiakServiceProvider extends ServiceProvider{
    /**
     * 服务提供者加是否延迟加载,默认为false
     *
     * @var bool
     */
    protected $isDeffer = true;
    
    /**
      * [$provide 绑定延迟加载的服务名称数组]
      * @var [type]
     */
     public $provide = [Connection::class];
    
    /**
     * [$events 触发延迟加载的事件]
     * @var [type] 
     */
     public $events = ['login', 'email'];

    /**
     * 注册服务提供者
     *
     * @return void
     */
    public function register()
    {
        $this->container->singleton(Connection::class, function ($app) {
            return new Connection($app['config']['riak']);
        });
    }

}

\Bobby\Component\Proxy\Event::fire('login');
//或者
\Bobby\Component\Proxy\Event::fire('email');

use App\Proxy;
use Bobby\Contract\Proxy\Proxy as ProxyContract;
use Bobby\Contract\Proxy\Proxy;
/**
 * 配置类代理
 */
class Log extends Proxy implements ProxyContract
{
	public static function getProxySubject()
	{
		//返回需要代理的容器绑定的服务名称
		return 'Log';
	}
}

\App\Proxy\Log::debug('test');