Run Application from the desired location - yii2 - php

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.

Related

Connecting slim php to mongodb doctrine

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);

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

Set the CORS configuration using Google Cloud Storage PHP API not working

I'm setting up Google Cloud Storage bucket CORS configuration using PHP API, but it doesn't seem to work
I read the document given in : https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/v0.96.0/storage/bucket
Here's my Laravel source code:
use Google\Cloud\Core\ServiceBuilder;
...
$projectId = 'myProjectId';
$bucketName = 'myBucketName';
$gcloud = new ServiceBuilder([
'keyFilePath' => 'resources/google-credentials.json',
'projectId' => $projectId
]);
$storage = $gcloud->storage();
$bucket = $storage->bucket($bucketName);
//change bucket configuration
$result = $bucket->update([
'cors' => [
'maxAgeSeconds' => 3600,
'method' => [
"GET","HEAD"
],
"origin" => [
"*"
],
"responseHeader" => [
"Content-Type"
]
]
]);
//print nothing and bucket doesn't changed
dd($bucket->info()['cors']);
After execute this code, the bucket CORS configuration doesn't changed
(My boss don't want me to use gsutil shell command to deal with this)
You're very close! CORS accepts a list, so you'll just need to make a slight modification:
$result = $bucket->update([
'cors' => [
[
'maxAgeSeconds' => 3600,
'method' => [
"GET","HEAD"
],
"origin" => [
"*"
],
"responseHeader" => [
"Content-Type"
]
]
]
]);
Let me know if it helps :).
The only thing I needed to change was when I config disks in laravel, using this code in config/filesystems.php when adding a disk for google:
'google' => [
'driver' => 's3',
'key' => 'xxx',
'secret' => 'xxx',
'bucket' => 'qrnotesfiles',
'base_url'=>'https://storage.googleapis.com'
]
Here is the code example fist get file contents from request:
$file = $request->file('avatar')
second save it into storage:
Storage::disk('google')->put('avatars/' , $file);

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']);

"migration directory does not exist" error when running Yii-user extension's migrations

I have a Yii framework installed by Composer, webapp in public_html folder and all libraries in vendor folder:
webroot
|
|_public_html
|
|_vendor
|
|_fierwebdesign
|
|_yii-user
|
|_migrations
My configuration in console.php is:
'modules'=>array(
'user'=>array(
'hash' => 'md5',
'sendActivationMail' => true,
'loginNotActiv' => false,
'activeAfterRegister' => false,
'autoLogin' => true,
'registrationUrl' => array('/user/registration'),
'recoveryUrl' => array('/user/recovery'),
'loginUrl' => array('/user/login'),
'returnUrl' => array('/user/profile'),
'returnLogoutUrl' => array('/user/login'),
),
),
When I try to run Yii-user extension's migrations, I'm getting error:
yiic.php migrate --migrationPath=vendor.fierwebdesign.yii-user.migrations
Error: The migration directory does not exist: vendor.fierwebdesign.yii-user.migrations
What am I doing wrong?
You need declare vendor alias in configs. If your console.php in public_html/config/ than declaration is:
Yii::setPathOfAlias('vendor', dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' .
DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '_vendor');
maybe this will help:
write something like this within the components array in the console.php config file;
'commandMap' => array(
'migrate' => array(
'class' => 'system.cli.commands.MigrateCommand',
'migrationPath' => 'application.modules.user.migrations',
// 'migrationTable' => 'tbl_migration',
'connectionID' => 'db',
// 'templateFile' => 'application.migrations.template',
),
and then give the command : php migrate
also, the app/modules/user/migartion folder must exist in this case and must contain migratio files
Best guess is that migrationPath actually refers to a file system path instead of to an alias like you are using

Categories