一段时间以来,我一直在寻找使用 php 框架来完成我的工作。直到最近我一直在写程序风格,并且仍在尝试在 oop 世界/风格中找到自己的方式。 我认为 php 框架可以帮助我编写更好的代码,而且我很确定在不久的将来我会倾向于 Laravel 项目。
现在我需要一个可以在现有代码中使用的数据库层。我现在使用带有准备好的语句的 mysqli,因为它很容易实现(之前使用 MySQL)。
我一直在看 http://medoo.in作为使用 pdo 包装器/类的“简单”方式,但支持页面上缺乏事件,以及我将来正在使用 Laravel 的事实,让我想知道我现在是否可以使用 Laravel 数据库层对于我现有的代码。
这可以做到吗?这是否有意义,还是我误解和混合了代码样式的概念?
最佳答案
IMO 逐步过渡到 OOP 方法是绝对有效的。
你的问题:
是的,您可以单独使用 Eloquent。
这里是打包网站:https://packagist.org/packages/illuminate/database
将 "illuminate/database": "5.0.*@dev"
添加到您的 composer.json
并运行 composer update
。
现在你需要引导 Eloquent。 (https://github.com/illuminate/database)
以下内容是从 repo 的自述文件中复制的:
使用说明
首先,创建一个新的“Capsule”管理器实例。 Capsule 旨在尽可能轻松地配置库以在 Laravel 框架之外使用。
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]);
// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Set the cache manager instance used by connections... (optional)
$capsule->setCacheManager(...);
// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();
// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();
一旦 Capsule 实例被注册。你可以这样使用它:
使用查询生成器
$users = Capsule::table('users')->where('votes', '>', 100)->get();
其他核心方法可以直接从 Capsule 以与 DB 门面相同的方式访问:
$results = Capsule::select('select * from users where id = ?', array(1));
使用架构生成器
Capsule::schema()->create('users', function($table)
{
$table->increments('id');
$table->string('email')->unique();
$table->timestamps();
});
使用 Eloquent ORM
class User extends Illuminate\Database\Eloquent\Model {}
$users = User::where('votes', '>', 1)->get();
有关使用此库提供的各种数据库工具的更多文档,请参阅 Laravel 框架文档。
关于php - 我可以独立使用 Laravel 的数据库层吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26083175/