Medoo

开始

更新日志

Where 语句

查询

聚合

Fetch

事务

管理

原生SQL查询

Raw object

PDO object

Debug

数据库信息

与其他框架协作

Medoo 可以与其他框架友好地协作。大多数全栈框架支持的单例设计模式是 Medoo 与那些在数据库实例中注册的框架协作的更好方式,只需一次引用,无需再次连接数据库即可重复使用。如果您使用的是支持的框架,我们建议您这样做。您可以阅读他们的官方文档,了解如何与第三方库协作以获取更多细节。

Laravel

Laravel 提供了一个单例函数来注册新的单例对象。您可以在那里创建并返回 Medoo 对象。数据库配置可以在配置文件中设置,并通过 Config::get() 加载回来。

在 app.php 上注册
// 使用 Medoo 命名空间。
use Medoo\Medoo;
 
// 注册为数据库。
$app->singleton('database', function () {
	return new Medoo([
		'type' => 'mysql',
		'host' => 'localhost',
		'database' => 'name',
		'username' => 'your_username',
		'password' => 'your_password'
	]);
});
访问 Medoo

通过单例注册后,您可以通过使用 $this->app->database 访问 Medoo 对象,并开始使用任何 Medoo API。

Route::get('/', function () {
 
	$data = $this->app->database->select('account', ['id', 'name']);
 
	return json_encode($data);
});

Slim

您可以将 Medoo 对象创建到应用的容器数组中,并通过 $this->database 访问它。

require './vendor/autoload.php';
 
use Medoo\Medoo;
 
$app = new \Slim\App();
 
$container = $app->getContainer();
 
$container['database'] = function () {
	return new Medoo([
		'type' => 'mysql',
		'host' => 'localhost',
		'database' => 'name',
		'username' => 'your_username',
		'password' => 'your_password'
	]); 
};
 
$app->get('/', function($request, $response, $args) {
 
	$data = $this->database->select('account', ['id', 'name']);
 
	return $response->write(json_encode($data));
});
 
$app->run();

Slim V4

最新版本的 Slim v4 已经改变了使用容器管理应用依赖的方式。您需要额外安装 PHP-DI 作为 Slim 的 AppFactory 的容器,并通过 $this->get('service') 访问 Medoo 服务。

确保 PHP-DI 已安装
$ composer require php-di/php-di
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
 
// 使用 PHP-DI 容器。
use DI\Container;
// 使用 Medoo。
use Medoo\Medoo;
 
require __DIR__ . '/vendor/autoload.php';
 
// 使用 PHP-DI 创建容器。
$container = new Container();
 
// 设置容器以在 AppFactory 上创建应用。
AppFactory::setContainer($container);
 
$app = AppFactory::create();
 
// 将数据库设置为 Medoo 服务的名称。
$container->set('database', function () {
	return new Medoo([
		'type' => 'mysql',
		'host' => 'localhost',
		'database' => 'name',
		'username' => 'your_username',
		'password' => 'your_password'
	]); 
});
 
$app->get('/', function (Request $request, Response $response, $args) {
 
	// 通过 $this->get('database') 访问 Medoo。
	$data = $this->get('database')->select('account', ['id', 'name']);
 
	return $response->write(json_encode($data));
});
 
$app->run();