如何解决将纤薄的 php 连接到 mongodb 学说
我将这个纤薄的 php 框架用于 mvc 结构。它也有教义联系https://github.com/semhoun/slim-skeleton-mvc
我想连接到我的 mongodb 服务器,这是学说 mongodb 包 https://www.doctrine-project.org/projects/mongodb-odm.html
我已经安装并设置了我的 bootstrap.php
,就像文档在设置步骤 https://www.doctrine-project.org/projects/doctrine-mongodb-odm/en/2.2/reference/introduction.html#setup
我的超薄框架中的设置文件是这样的
<?php
declare(strict_types=1);
use DI\ContainerBuilder;
use Monolog\Logger;
return function (ContainerBuilder $containerBuilder) {
$rootPath = realpath(__DIR__ . '/..');
// Global Settings Object
$containerBuilder->addDefinitions([
'settings' => [
// Base path
'base_path' => '',// Is debug mode
'debug' => (getenv('APPLICATION_ENV') != 'production'),// 'Temprorary directory
'temporary_path' => $rootPath . '/var/tmp',// Route cache
'route_cache' =>$rootPath . '/var/cache/routes',// View settings
'view' => [
'template_path' =>$rootPath . '/tmpl','twig' => [
'cache' =>$rootPath . '/var/cache/twig','debug' => (getenv('APPLICATION_ENV') != 'production'),'auto_reload' => true,],// doctrine settings
'doctrine' => [
'meta' => [
'entity_path' => [ $rootPath . '/src/Entity' ],'auto_generate_proxies' => true,'proxy_dir' => $rootPath . '/var/cache/proxies','cache' => null,'connection' => [
'driver' => 'pdo_sqlite','path' => $rootPath . '/var/blog.sqlite'
]
],// monolog settings
'logger' => [
'name' => 'app','path' => getenv('docker') ? 'php://stdout' : $rootPath . '/var/log/app.log','level' => (getenv('APPLICATION_ENV') != 'production') ? Logger::DEBUG : Logger::INFO,]
],]);
if (getenv('APPLICATION_ENV') == 'production') { // Should be set to true in production
$containerBuilder->enableCompilation($rootPath . '/var/cache');
}
};
如何连接到我的 mongodb 服务器并在我的控制器中使用它?
解决方法
确保 ext-mongodb
处于停顿状态。
extension=mongodb
安装 Doctrine MongoDB ODM 库:
composer require doctrine/mongodb-odm
为 DocumentManager::class
添加 DI 容器定义:
<?php
use Doctrine\ODM\MongoDB\Configuration;
use Doctrine\ODM\MongoDB\DocumentManager;
use MongoDB\Client;
use Psr\Container\ContainerInterface;
return [
// ...
DocumentManager::class => function (ContainerInterface $container) {
$settings = $container->get('settings')['mongodb'];
// URI: mongodb://127.0.0.1
$client = new Client($settings['uri']);
$config = new Configuration();
// ...
return DocumentManager::create($client,$config);
},];
然后使用依赖注入并在您的 Repository 类构造函数中声明 DocumentManager
。
用法示例:
$address = new Address();
$address->setAddress('555 Doctrine Rd.');
$address->setCity('Nashville');
$address->setState('TN');
$address->setZipcode('37209');
$this->dm->persist($address);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。