jwh315 / laravel-capsule-wrapper
使用Eloquent ORM在Laravel框架之外,利用现有的PDO数据库连接。
0.0.1
2017-06-19 00:58 UTC
Requires
- illuminate/database: ^5.4
- illuminate/events: ^5.4
This package is not auto-updated.
Last update: 2024-09-29 03:47:04 UTC
README
使用Eloquent ORM在Laravel框架之外,利用现有的PDO数据库连接。
免责声明
该项目目前仅是一个概念验证,没有经过测试。我已手动使用一些标准的Laravel操作进行测试并取得成功,但我目前无法保证其在实际PHP应用程序中的健壮性。
我尚未完全解决的问题之一是数据库名称参数,这是您通常会传递给Eloquent连接的。我选择省略此参数,因为我的用例需要一个数据库连接,能够访问同一连接上的多个数据库。从我的有限测试来看,这并没有造成问题,但我可能遗漏了一些内容。
最后,目前这仅适用于MySQL。这是在 CapsuleManager\Wrapper\DatabaseManager::addDefaultConnection()
中实现的,理论上您应该可以根据需要替换任何其他的 Illuminate\Database
连接类。
安装
composer require jwh315/laravel-capsule-wrapper
用法
这基本上与Illuminate\Database存储库中的用法说明相同。需要注意的是,我尚未测试Schema Builder
use CapsuleManager\Wrapper\Manager;
use Illuminate\Container\Container;
use Illuminate\Events\Dispatcher;
$dsn = "mysql:host=" . DBHOST;
$pdo = new \PDO($dsn, DBUSER, DBPASS);
$capsule = new Manager($pdo);
// Set the event dispatcher used by Eloquent models... (optional)
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();
// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();
$t = $capsule::table('mysql.db')
->where('Host', 'localhost')
->get();
dd($t);
我还添加了一个静态访问器,以在包装类内部封装所有这些样板代码,如果您要使用上述示例中的默认设置,这也将有效。
use CapsuleManager\Wrapper\Manager as Capsule;
$dsn = "mysql:host=" . DBHOST;
$pdo = new \PDO($dsn, DBUSER, DBPASS);
$capsule = Capsule::init($pdo);
$t = $capsule::table('mysql.db')
->where('Host', 'localhost')
->get();
dd($t);
使用Eloquent ORM
这完全符合您的预期,除了如上所述,我没有添加设置数据库名称的方法,因此您必须显式设置它。
//initialize the capsule manager
use CapsuleManager\Wrapper\Manager as Capsule;
$dsn = "mysql:host=" . DBHOST;
$pdo = new \PDO($dsn, DBUSER, DBPASS);
$capsule = Capsule::init($pdo);
//user model example
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
//this needs to be set on all your models
protected $table = 'test.users';
}
//using the user model
dd(User::all()->last()->login);