Yii2 custom component namespace - yii2

I have a component class located in the following path:
#backend/components/component-name/ComponentClass.php
and want to use default namespace for this class:
namespace backend\components;
I've tried to set aliases in my confing/main.php:
...
'aliases' => [
'#backend/components' => '#backend/components/component-name'
],
...
but I know that's wrong decision, because it's broke the namespace logic for the other classes located in backend/components.
How can I set the same namespace backend\components for both classes in #backend/components and #backend/components/component-name?

I suggest to use composer autoloader for this task - it works fine even if you provide multiple possible paths for single class. Edit your composer.json autoload section to something like:
"autoload": {
"psr-4": {
"backend\\": "backend/",
"backend\\components\\": "backend/components/component-name/",
...
}
},
And run in console:
composer dump-autoload
Make sure that you're loading composer autoloader in your index.php:
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';

Related

Yii2 How to correctly register a CSS file

I'm trying to register a CSS file in this way
$this->registerCssFile('../node_modules/fullcalendar/dist/fullcalendar.css', [
'depends' => [\yii\web\JqueryAsset::className()]
]);
But I get the error:
Failed to load a resource.
For instance, I know that I am standing at web folder, so that's why I wrote the above code in that way.
I tried without the registerCssFile and I achieved it writing directly this in the view file:
<link href="../node_modules/fullcalendar/dist/fullcalendar.css" rel="stylesheet">
Therefore I think the error is in the registerCssFile cause when I inspect in the browser this method add a slash (/) before all the relative path:
<link href="/../node_modules/fullcalendar/dist/fullcalendar.css" rel="stylesheet">
Anyway, THE QUESTION is how can I do to achieve it with regiserCssFile(the correct way)?
Or how can I remove that slash?
Just in case:
/yii2app
|_/views
|_/whatever
|_myview.php
|_/web
|_/node_modules
|_/fullcalendar
|_/dist
|_fullcalendar.css
The first thing that I would advise you is to move the folder inside the web directory and remove the trailing ../ from the URL.
Like below
$this->registerCssFile('node_modules/fullcalendar/dist/fullcalendar.css', [
'depends' => [\yii\web\JqueryAsset::className()]
]);
The /yii2app/web directory is where your application Entry script is running from so you do not need to provide a path relative to the view file, but the web directory.
Otherwise, use AssetManager to load assets from outside the web directory and use the $sourcePath option to use the directory outside the web.
see below a demo for Asset manager.
namespace app\assets;
use Yii;
use yii\web\AssetBundle;
use yii\web\View;
// set #themes alias so we do not have to update baseUrl every time we change themes
Yii::setAlias('#themes', Yii::$app->view->theme->baseUrl);
/**
* Main frontend application asset bundle.
*/
class FullCalendarAsset extends AssetBundle
{
public $sourcePath = '#app/node_modules/';
public $css = [
'fullcalendar/dist/_fullcalendar.css',
];
public $js = [
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
'yii\bootstrap\BootstrapPluginAsset',
];
}
place the above file inside the app/assets directory and then inside your view
use app\assets\FullCalendarAsset;
FullCalendarAsset::register($this);
you should learn about the application LIFE CYCLE.

Upgrading Laravel 4.2 to 5.0, getting [ReflectionException] Class App\Http\Controllers\PagesController does not exist

I was updating my project from laravel 4.2 to laravel 5.0. But, after I am facing this error and have been trying to solve it for the past 4 hours.
I didn't face any error like this on the 4.2 version. I have tried composer dump-autoload with no effect.
As stated in the guide to update, I have shifted all the controllers as it is, and made the namespace property in app/Providers/RouteServiceProvider.php to null. So, I guess all my controllers are in global namespace, so don't need to add the path anywhere.
Here is my composer.json:
"autoload": {
"classmap": [
"app/console/commands",
"app/Http/Controllers",
"app/models",
"database/migrations",
"database/seeds",
"tests/TestCase.php"
],
Pages Controller :
<?php
class PagesController extends BaseController {
protected $layout = 'layouts.loggedout';
public function getIndex() {
$categories = Category::all();
$messages = Message::groupBy('receiver_id')
->select(['receiver_id', DB::raw("COUNT('receiver_id') AS total")])
->orderBy('total', 'DESC'.....
And, here is BaseController.
<?php
class BaseController extends Controller {
//Setup the layout used by the controller.
protected function setupLayout(){
if(!is_null($this->layout)) {
$this->layout = View::make($this->layout);
}
}
}
In routes.php, I am calling controller as follows :
Route::get('/', array('as' => 'pages.index', 'uses' => 'PagesController#getIndex'));
Anyone please help. I have been scratching my head over it for the past few hours.
Routes are loaded in the app/Providers/RouteServiceProvider.php file. If you look in there, you’ll see this block of code:
$router->group(['namespace' => $this->namespace], function($router)
{
require app_path('Http/routes.php');
});
This prepends a namespace to any routes, which by default is App\Http\Controllers, hence your error message.
You have two options:
Add the proper namespace to the top of your controllers.
Load routes outside of the group, so a namespace isn’t automatically prepended.
I would go with option #1, because it’s going to save you headaches in the long run.

Yii2 How to enable default assets only in certain modules

I am using basic yii2 app, I have disabled the boostrap css and js in web.php config but i want to enable it inside the module called admin.
I tried adding like this, for component section in config.php under admin module folder, but no luck!
'assetManager' => [
'bundles' => [
'yii\bootstrap\BootstrapPluginAsset' => [
'js'=> ['js/boostrap.js']
],
'yii\bootstrap\BootstrapAsset' => [
'css' => ['css/boostrap.min.css']
]
],
],
How can i achieve this?
In your module's init() method, you can override an exist asset bundle like below:
public function init() {
\Yii::$app->assetManager->bundles['yii\bootstrap\BootstrapAsset'] = [
'css' => ['css/bootstrap_NEW.css']
];
parent::init();
}
In above example, we override yii\bootstrap\BootstrapAsset CSS file in our module. So, in this module, it uses bootstrap_NEW.css instead of its default.
Please note that, you can do this in application globally, not specially in module's init() method. It was just a suggestion to solve this specific case.
You should use asset bundles to handle this, no need to modify assetManager.
To disable Bootstrap, simply remove it from $depends in AppAsset :
public $depends = [
'yii\web\YiiAsset',
];
Create a ModuleAsset class in your module :
class ModuleAsset extends \yii\web\AssetBundle
{
public $depends = [
'yii\bootstrap\BootstrapAsset',
];
}
Make sure to register it in your module's views (you could use a custom layout) :
ModuleAsset::register($this);
Read more : http://www.yiiframework.com/doc-2.0/guide-structure-assets.html

Namespaced helper won't load in Laravel 4

I have a controller that calls a helper class in my app/helpers directory and then that helpers calls another class within it's namespace, but it can't find that class.
So here is my controller:
<?php
namespace App\Controllers\Dash;
use \App\Models\SalesFlyer;
use \App\Helpers\MyPdf;
class FlyerBuilderController extends BaseController {
public function getPdf($flyerId = null) {
$flyer = new SalesFlyer();
$flyerData = $flyer->getSalesFlyerName($flyerId);
$flyerPath = public_path().'/assets/media/flyers/'.Session::get('userid').'/'.$flyerData->name.'-'.$flyerId.'.html';
return MyPdf::downloadPdf($flyerPath, $flyerData->name);
}
}
It catches MyPdf class perfectly fine. Here is MyPdf class:
<?php
namespace App\Helpers;
class MyPdf {
public static function downloadPdf($filePath, $filename) {
$client = new PdfCrowd("anthonythomas", "1ebd0d6e3ec1dfa83a6c5f3dd32906f0");
// other code here
}
}
The PdfCrowd class is within App\Helpers namespace like so:
<?php
namespace App\Helpers;
//
// Pdfcrowd API client.
//
class PdfCrowd { }
Class 'App\Helpers\PdfCrowd' not found
Here is my start/global.php file:
<?php
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/controllers/dash',
app_path().'/controllers/dash/product',
app_path().'/models/Product',
app_path().'/models',
app_path().'/database/seeds',
app_path().'/helpers',
));
Then here is my composer:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/controllers/dash",
"app/controllers/dash/product",
"app/models",
"app/models/Product",
"app/helpers",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
}
Any idea why I'm getting that error?..
Everything looks fine but you also have to remember to
composer dump-autoload
Every time you create a new class. Also, check the file
vendor/composer/autoload_classmap.php
You must see your Helper class there.
But if you use PSR-4, you can use the same namespace and you won't have execute composer dump-autoload again:
"autoload": {
"psr-4": {
"App\\Helpers\\": "app/helpers"
}
},
Just remember to remove "app/helpers", from the classmap.
Ok for a shared hosting provider... EVERYTIME you add a new namespace and update composer even with psr-4 it seems, you have to replace the vendor directory with the current one on your local machine for it to actually go through! This saved me so much hours of time after I realized I had to replace the vendor directory everytime a composer dump-autoload was issued locally.

Errors after namespace addition. Unable to access models

I had to incorporate namespacing into my project because I need to use a model named 'Event', and so to avoid errors with the pre-defined 'Event' used by Laravel.
Composer.json:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
},
"psr-0": {
"App": "app/models/"
},
User model:
<?php
namespace App;
use Eloquent;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
Directory structure pointing towards models:
models/app/User.php
Error on trying to 'sign-in' (This was working before the need for namespacing):
Symfony \ Component \ Debug \ Exception \ FatalErrorException
Class '\User' not found
Sign-in function:
public function postSignin(){
if (Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password')))) {
$title = Auth::user()->title;
$surname = Auth::user()->surname;
I have run the command 'composer dump-autload' after editing the composer.json file.
Any help would be hugely appreciated as to why this isn't working any more.
If you are following psr-0 then your directory structure of your models should be:
app/
models/
App/
User.php
and try to set the model in config, go to: app/config/auth.php
change the model
'model' => '\App\User'
Good Luck !.