Connecting slim php to mongodb doctrine - php

I am using this slim php skeleton for an mvc structure. It has doctrine connection as well https://github.com/semhoun/slim-skeleton-mvc
I want to connect to my mongodb server and this is the doctrine mongodb package https://www.doctrine-project.org/projects/mongodb-odm.html
I have it installed and setup my bootstrap.php like the docs say on the setup step https://www.doctrine-project.org/projects/doctrine-mongodb-odm/en/2.2/reference/introduction.html#setup
The settings file in my slim framework looks like this
<?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');
}
};
How can i connect to my mongodb server and use it in my controllers?

Make sure that ext-mongodb in stalled.
extension=mongodb
Install the Doctrine MongoDB ODM library:
composer require doctrine/mongodb-odm
Add a DI container definition for DocumentManager::class:
<?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);
},
];
Then use dependency injection and declare DocumentManager in your Repository class constructor.
Usage example:
$address = new Address();
$address->setAddress('555 Doctrine Rd.');
$address->setCity('Nashville');
$address->setState('TN');
$address->setZipcode('37209');
$this->dm->persist($address);

Related

Run Application from the desired location - yii2

This is my project structure
project1
-assets
-commands
.
.
.
modules
-people
-controllers
-PeopleController.php
-models
-views
People.php
web
-index.php
I'm deploying it to server. URL hit: https://11.11.11.11/project1/web/index.php/people/people/index
Where should I modify in server files, so that URL: https://11.11.11.11/people/people/index works for me? I don't want user to know the folder name where my codes are available.
The answer varies depending on the type of server you use or the use of shared hosting
You can use this tutorial to configure the server.
To remove web and index.php Or ... :
Add the following code to the config/web.php file:
use \yii\web\Request;
$baseUrl = str_replace('/web', '', (new Request)->getBaseUrl());
$config = [
#code...
'components' => [
// ...
'request' => [
// ...
'baseUrl' => $baseUrl, // Add baseUrl
],
// ...
'urlManager' => [
'baseUrl' => $baseUrl, // Add baseUrl
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
// ...
],
],
// ...
],
]
Tutorial on this page can also help.

Slim v4 Creating Log File

So, my issue is that I'm having trouble to make Slim record all its actions inside a file (for example : app.log). I ran across a lot of tutorials and other forum similar to this one but the issue was that they were using the v3 of the Slim Framework.
I saw some post suggesting things like this inside a settings.php :
return [
'settings' => [
'displayErrorDetails' => true, // set to false in production
'addContentLengthHeader' => false, // Allow the web server to send the content-length header
// Renderer settings
'renderer' => [
'template_path' => __DIR__ . '/../templates/',
],
// Monolog settings
'logger' => [
'name' => 'my-app',
'path' => __DIR__ . '/../logs/' . $logDate->format('Y-m-d') . 'app.log',
],
],
];
But the issue with that method is that, well, settings aren't set up this way anymore in v4. So here I am. Stuck. If anybody could give me a hand, it'll help a lot !
To load the settings within a container you have to add a container definition for it.
Example settings file: config/settings.php
return [
// set to false in production
'displayErrorDetails' => true,
// Renderer settings
'renderer' => [
'template_path' => __DIR__ . '/../templates/',
],
// Monolog settings
'logger' => [
'name' => 'my-app',
'path' => __DIR__ . '/../logs/' . date('Y-m-d') . '_app.log',
],
];
Example container entry in config/container.php:
use Psr\Container\ContainerInterface;
// ...
return [
// ...
'settings' => function () {
return require __DIR__ . '/settings.php';
},
// Add more entries here ...
}
To fetch the settings within the container use this:
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
// ...
return [
// ...
LoggerInterface::class => function (ContainerInterface $container) {
$settings = $container->get('settings');
$name = $settings['logger']['name'];
$logger = new Logger($name);
// Add logger handler...
return $logger;
},
// ...
}
Tip: For autowiring support it's better to use an collection object instead of an simple "string" as container identifier. Read more

CKFinder3 dynamically change folder path

Is there anyway to change the baseUrl of CKFinder dynamically?
I need to use this kind of path: /websitebuilder/www/user_images/$id/. I used google to find some answer, but I didn't manage to make it works.
Can someone please give me any hint how should I do that?
I know that in config.php you change the baseUrl param, but how to make it dinamically?
Hi you can use the example for different folder per instance CKFinder 3 HOWTO.
Basically you should update you config.php to something like this:
$id = getID();
$config['backends'][] = array(
'name' => 'default',
'adapter' => 'local',
'baseUrl' => 'http://example.com/ckfinder/userfiles/' . $id,
'root' => '/path/to/ckfinder/userfiles/' . $id
);
1 create new middleware:
php artisan make:middleware DynamicCkfinderConfig
with this code in the handel function :
not forget to 'use Auth' in the top of file;
public function handle(Request $request, Closure $next)
{
if (auth()->check()) {
config([
'ckfinder.backends.default' => [
'name' => 'default',
'adapter' => 'local',
'baseUrl' => '/user-' . md5(Auth::user()->id) . '/',
'root' => public_path('/user-' . md5(Auth::user()->id) . '/'),
'chmodFiles' => 0777,
'chmodFolders' => 0755,
'filesystemEncoding' => 'UTF-8'
]
]);
}
return $next($request);
}
2 add the middleware in the kernel.php file
protected $routeMiddleware = [
'ckfinderConfig' => \App\Http\Middleware\DynamicCkfinderConfig::class,
];
3 use the middleware in the ckfinder connector route
Route::any('/ckfinder/connector', [CKFinderController::class, 'requestAction'])
->name('ckfinder_connector')->middleware(['ckfinderConfig']);

Slim 3 - Error is not shown

I am trying to use zeuxisoo/slim-whoops to show errors, but for some reason I am only getting white screen without any message show. This is the code I am using (I don't know if it does matter, I am using quick PHP host (php -S localhost:8000):
require __DIR__ . '/../vendor/autoload.php';
$app = new Slim\App([
'settings' => [
'displayErrorDetails' => true,
'debug' => true,
'whoops.editor' => 'sublime',
]
]);
$app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware);
Make sure that your file begins with <?php and that after your $app->add(...); you call $app->run();:
<?php
require __DIR__ . '/../vendor/autoload.php';
$app = new Slim\App([
'settings' => [
'displayErrorDetails' => true,
'debug' => true,
'whoops.editor' => 'sublime',
]
]);
$app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware);
$app->run();

ACL not applying during AWS s3 folder upload (uploadDirectory)

For some reason public-read is not being applied when I'm uploading a folder to an S3 bucket. (IE, public can not access the files)
The files upload fine, but they are all set to private. Tried everything I can think of. Feels like I'm missing something basic.
Was using this guide:
https://blogs.aws.amazon.com/php/post/Tx2W9JAA7RXVOXA/Syncing-Data-with-Amazon-S3
Here is my code:
require '../vendor/autoload.php';
use Aws\S3\S3Client;
$client = S3Client::factory(array(
'version' => '2006-03-01',
'region' => 'ap-southeast-2',
'credentials' => array(
'key' => 'MYKEY',
'secret' => 'MYSECRET',
)
));
$dir = 'assets';
$bucket = 'gittestbucket';
$keyPrefix = 'assets';
$options = array(
'params' => array('ACL' => 'public-read'),
'concurrency' => 20,
'debug' => true
);
$UploadAWS = $client->uploadDirectory($dir, $bucket, $keyPrefix, $options);
var_dump($UploadAWS);
My IAM user policy (also has a group of list all buckets):
{
"Statement": [
{
"Action": "s3:*",
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::gittestbucket",
"arn:aws:s3:::gittestbucket/*",
]
}
]
}
Any help much appreciated. Cheers
I struggled with this a while back.
Try changing you upload statement to this one bellow
$UploadAWS = $client->uploadDirectory($dir, $bucket, $keyPrefix, array(
'concurrency' => 20,
'debug' => true,
'before' => function (\Aws\Command $command) {
$command['ACL'] = strpos($command['Key'], 'CONFIDENTIAL') === false
? 'public-read'
: 'private';
}
));
AWS is shocking sometimes for its documentation as it changes so much

Categories