我可以单独使用Laravel的数据库层吗?

sjo*_*sen 27 php mysql laravel

一段时间以来,我一直在寻找使用php框架来完成我的工作.直到最近我一直在编写程序风格,并且仍然试图找到我的方式围绕oop世界/风格.我认为一个php框架可以帮助我编写更好的代码,我很确定我会在不久的将来倾向于Laravel项目.

现在我需要一个可以在现有代码中使用的数据库层.我现在使用mysqli和准备好的语句,因为我很容易实现(之前使用MySQL).

我一直在看http://medoo.in作为一种"简单"的方式来使用pdo包装器/类,但支持页面缺乏活动,以及我将来正在使用Laravel的事实,让我想知道我现在是否可以将Laravel数据库层用于现有代码.

这可以做到并且它有意义还是我误解和混合代码样式的概念?

Bas*_*ann 45

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();
Run Code Online (Sandbox Code Playgroud)

一旦Capsule实例已注册.您可以像这样使用它:

使用查询生成器

$users = Capsule::table('users')->where('votes', '>', 100)->get();
Run Code Online (Sandbox Code Playgroud)

其他核心方法可以直接从Capsule访问,方式与数据库外观相同:

$results = Capsule::select('select * from users where id = ?', array(1));
Run Code Online (Sandbox Code Playgroud)

使用Schema Builder

Capsule::schema()->create('users', function($table)
{
    $table->increments('id');
    $table->string('email')->unique();
    $table->timestamps();
});
Run Code Online (Sandbox Code Playgroud)

使用雄辩的ORM

class User extends Illuminate\Database\Eloquent\Model {}

$users = User::where('votes', '>', 1)->get();
Run Code Online (Sandbox Code Playgroud)

有关使用此库提供的各种数据库工具的更多文档,请参阅Laravel框架文档.