How can I specify the relative path in php? - php

I have registration.phtml file in src/Mess/View/pages and registrationView.php in src/Mess/View/Views. How can i specify the relative path to the registration.phtml file in the registrationView.php file?
This is code i registrationView.php`
class RegistrationView extends View
{
public ValidationAttributes $validation;
public function __construct(Action $registration)
{
parent::__construct(src/Mess/View/pages/registration.phtml', [
'registration' => $registration,
]);
$this->validation = $registration->validationAttributes([
'login',
'password',
'passwordRepeat',
'firstName',
'lastName',
'email',
'phoneNumber',
'birthDate',
'gender',
'avatar',
]);
}

I assume that you use the given string in the parent::__construct as a path.
parent::__construct(__DIR__ . '/../pages/registration.phtml', [
'registration' => $registration,
]);

You should be getting a parse error because of a missing quote, plus the src directory is by no means a child of Views:
src
Mess
View
pages
registration.phtml
Views
registrationView.php
My advice is that you don't use relative paths, they're very hard to manage when you start nesting includes. You can use the __DIR__ the magic constant and the dirname() function to build absolute paths:
echo dirname(__DIR__) . '/pages/registration.phtml';
Running this from src/Mess/View/Views/registrationView.php will print
/path/to/project/src/Mess/View/pages/registration.phtml, which is valid no matter current working directory.
But everything will be easier if you create some utility constants that allow you to forget about relatives paths once and for all, as in:
parent::__construct(PROJECT_ROOT . PAGES . 'registration.phtml', [
'registration' => $registration,
]);
// PROJECT_ROOT is `/path/to/project/`
// PAGES is `pages/`
Or just:
parent::__construct(PAGES . 'registration.phtml', [
'registration' => $registration,
]);
// PAGES is `/path/to/project/src/Mess/View/pages/`

Related

Codeigniter 4 - Cannot get my module to work

I am trying to get a simple module working. All it does is echo 'test' to a web page but I cannot get it working.
The first thing I did was add the module to app/Config/Autoload.php as follows;
public $psr4 = [
APP_NAMESPACE => APPPATH, // For custom app namespace
'Config' => APPPATH . 'Config',
'Modules\Filemanager' => ROOTPATH . 'modules'
];
Then, I created the following directory structure;
In Modules/Filemanager/Config/Routes.php I have added following route;
<?php
$routes->add('/filemanager/(:any)', 'Modules\Filemanager\Controllers\Filemanager::index');
Lastly, in Modules/Filemanager/Controllers/Filemanager I have the following method:
<?php
namespace Modules\Filemanager\Controllers;
use App\Controllers\BaseController;
class Filemanager extends \App\Controllers\BaseController
{
public function index(){
echo 'test'; die();
}
}
When I go to my browser and enter example.com/filemanager/index I get the following error;
Controller or its method is not found: \App\Controllers\Filemanager::index
Any ideas would be much appreciated.
You've done few things wrong here.
In the App/Config/Autoload.php,
you've written 'Modules\Filemanager' => ROOTPATH . 'modules'
But in your directory structure image, there is no directory with the name 'modules'
Please change the 'Modules' folder name to 'modules'
Change 'Modules\Filemanager' => ROOTPATH . 'modules' to
'Modules' => ROOTPATH . 'modules' in App/Config/Autoload.php
In the Modules/Filemanager/Config/Routes.php
You're using the $routes variable in the below line
$routes->add('/filemanager/(:any)', 'Modules\Filemanager\Controllers\Filemanager::index'); But $routes is not defined anywhere in the file.
Put
if(!isset($routes)) {
$routes = App\Config\Services::routes(true);
}
$routes->get('/filemanager/(:any)', 'Modules\Filemanager\Controllers\Filemanager::index');
It should be $routes->get() instead of $routes->add()
Module level routing will not work until you add these routes in the App\Config\Routes.php file.
To add your modules routes to the app\Config\Routes.php
foreach(glob(ROOTPATH . 'modules/*', GLOB_ONLYDIR) as $item_dir) {
if(file_exists($item_dir . '/Config/Routes.php')) {
require_once($item_dir . '/Config/Routes.php');
}
}
After these changes your code should work.

yii2 jasper on basic template

I've followed step by step instructions from JasperReports for yii2.
Installed JDK 1.8 on my Debian 8
Setted up mysql connector's classpath in /etc/profile
Added chrmorandi/yii2-jasper to my composer and updated
I guess php exec() function is enabled because the following test in any view resolves successfuly ...
<? echo exec('whoami'); ?>
chromandi is now under /vendors
java -version says 1.8.0_111
$CLASHPATH points to /usr/share/mysql-connector-java/mysql-connector-java-5.1.40-bin.jar
configuration is so ...
'components' => [
'jasper' => [
'class' => 'chrmorandi\jasper',
'db' => [
'host' => 'localhost',
'port' => 3306,
'driver' => 'mysql',
'dbname' => 'acme',
'username' => 'acme',
'password' => 'acme'
]
],
...
]
I added a controller like this ...
<?php
namespace app\controllers;
use Yii;
use chrmorandi\Jasper;
class EstadisticasController extends \yii\web\Controller {
public function actionIndex() {
// Set alias for sample directory
Yii::setAlias('example', '#vendor/chrmorandi/yii2-jasper/examples');
/* #var $jasper Jasper */
$jasper = Yii::$app->jasper;
// Compile a JRXML to Jasper
$jasper->compile(Yii::getAlias('#example') . '/hello_world.jrxml')->execute();
// Process a Jasper file to PDF and RTF (you can use directly the .jrxml)
$jasper->process(Yii::getAlias('#example') . '/hello_world.jasper', [
'php_version' => 'xxx'
], [
'pdf',
'rtf'
], false, false)->execute();
// List the parameters from a Jasper file.
$array = $jasper->listParameters(Yii::getAlias('#example') . '/hello_world.jasper')->execute();
// return pdf file
Yii::$app->response->sendFile(Yii::getAlias('#example') . '/hello_world.pdf');
}
}
and tested http://www.acme.es/estadisticas/index that is supposed to be a built-in example.
Now it comes the problem. It complains about
$jasper = Yii::$app->jasper;
line. The output says
ReflectionException Class chrmorandi\jasper does not exist
Anyone facing this issue? There is no much info about jasper on Yii. Any help would be welcome.
Thank you.
Finally the solution was changing
$jasper = Yii::$app->jasper;
to
$jasper = new \chrmorandi\jasper\Jasper();
Don't know why in the yii2-jasper documentation is setted so if it does not work. Anyway you can make it work following my above compilation.
As the
use chrmorandi\Jasper
is not working properly
You will have to change Jasper.php setting in the init function this
$componentes = Yii::$app->components;
$this->db = $componentes['jasper']['db'];
to make it work.
Editing under vendors is not something I want to do. In order to prevent these fixes I moved from chrmorandi's extension (until its improvement) to cossou/jasperphp extension.
So far the cossou's extension reaches all my goals.
I hope this helps somebody.

Yii2 how to change default aliaes #vendor ==#app/vendor to #webroot/vendor

now the default aliaes
#vender Defaults to #app/vendor.
how to change it defaults to #webroot/vendor.
ignore below info
when using assetsBundle in the namespace repo.
namespace repo\assets;
use yii\web\AssetBundle;
class RepoAsset extends AssetBundle {
public $sourcePath = '#repo/media';
public $css = [
'css/site.css',
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
I can't publish the depends asset.
The file or directory to be published does not exist: /Users/tyan/Code/php/myii/repo/vendor/bower/jquery/dist
but the real location of the jquery is
/Users/tyan/Code/php/myii/vendor/bower/jquery/dist
it this happends to bootstrapAsset too.I try to echo the
#app //seems it's location is /Users/tyan/Code/php/myii/repo
#vendor //it's /Users/tyan/Code/php/myii/repo/vendor
seems that #app and #vendor add my own namespace in it automatically which not make sence.
BTW. I define the #repo aliases in the web.php config file.
'aliases' => [
'#repo' => dirname(__DIR__),
],
'controllerNamespace' => 'repo\\controllers',
because I want to change the default namespace.

Lines of code duplicated in Controller, where to create a method with them?

Aloha, I have two methods in my Controller, one for setting the profile picture and the other for updating it. I'm using this lines of code in both methods:
$user = Auth::user();
if (Input::file('image')) {
$image = Image::make(Input::file('image'));
$fullName = Input::file('image')->getClientOriginalName();
$extension = Input::file('image')->getClientOriginalExtension();
$pathToCreate = public_path() .'/images/'. $user->email . '/';
$fullPath = $pathToCreate . $user->email . '.' . $extension;
$pathDatabase = 'images/' . $user->email . '/' . $user->email . '.' .$extension;
// Creating directory if it does not exists
File::exists($pathToCreate) or File::makeDirectory($pathToCreate);
$image->resize(null, 145, function ($constraint) { $constraint->aspectRatio(); })
->crop(130,130)
->save($fullPath);
$user->picture = $pathDatabase;
I want to create a method with this lines of code but I feel that the controller is not a good place for it. Where should I place this method?
Generally speaking, it depends on the purpose of the code. If this is the only place on your site that you'll be using that code, it is perfectly acceptable to include the code a private method in the Controller class.
If this code will be used in other controllers, you probably want to create a service class to handle this. This would equate to something like the following when used in your controller:
$user->picture = $this->fileUploadService->process( Input::file('image') );
The extremely short answer is: put it where it makes the most sense. A generic solution should be broadly available as a service. A specific solution should go where ever that specificity is needed (controller, repository, model, etc.).
You should check out Laravel-Stapler. Very useful for handling image uploads in Laravel. https://github.com/CodeSleeve/laravel-stapler
Rather then saving an image and checking if it exists you can attach (or "Staple") an image to a model.
An example taken from the docs on how to setup the form is below.
<?= Form::open(['url' => action('UsersController#store'), 'method' => 'POST', 'files' => true]) ?>
<?= Form::input('first_name') ?>
<?= Form::input('last_name') ?>
<?= Form::file('picture') ?>
<?= Form::submit('save') ?>
<?= Form::close() ?>
The model would have something like this in the controller:
$this->hasAttachedFile('picture', [
'styles' => [
'thumbnail' => '100x100',
'large' => '300x300',
'pictureCropped' => '75x75#'
],
'url' => '/system/:attachment/:id_partition/:style/:filename',
'default_url' => '/:attachment/:style/missing.jpg'
]);
Then all you do in the controller is User::create(Input::all());
Checking existence of "attachments" is as easy as if ($user->picture) ...
So the saving of the file is already taking care of by Stapler and the cropping is done automatically via the 'pictureCropped' => '75x75#' configuration. This should remove enough of the code that you don't need to make another method.
Hope this helps!

Yii2 assetManager appendTimestamp not working properly

I am using appendTimestamp of assetManager component
'assetManager' => [
//append time stamps to assets for cache busting
'appendTimestamp' => true,
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
It correctly adds the timestamp after each asset as shown:
<link href="/frontend/web/assets/7b3fec74/css/arabic.css?v=1428761706" rel="stylesheet">
However when I make changes to that CSS file, the timestamp does not update. Is this because of the FileCache?
Every time I wish to test my new changes, I currently need to clear the contents of my web/assets folder
Am I required to delete the contents of the assets folder every time I wish to test my new assets?
I had same problem when I used $sourcePath as files source in my asset bundle. I solved it buy adding $publishOptions. Making 'forceCopy'=>true forces files to be published in assets folder each time:
class Asset extends AssetBundle
{
public $sourcePath = '...';
public $js = [..];
public $css = [...];
public $depends = [...];
public $publishOptions = [
'forceCopy' => true,
//you can also make it work only in debug mode: 'forceCopy' => YII_DEBUG
];
}
The FileCache component you referred to - has nothing to do with the assets. It is responsible with your defined cache items :
Yii::$app->cache->set('key', 'value')
Yii::$app->cache->get('key')
...
So there might be a problem with your assetManager.

Categories