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.
Related
I am working on a requirement of where I have to include all common methods like pagination, etc. which were used in my views into all my views. For this purpose I thought helper file is useful and created helper file in common\helpers\ directory with name Common as helper file name. I am facing difficulty in using this helper file in my view file.
I have included this helper file in my view as
use common\helpers\Common;
When I open the page I am getting error as "Class 'common\helpers\Common' not found"
My helper file: Common.php
namespace common\helpers;
class Common
{
protected $_file;
protected $_data = array();
public function __construct($file)
{
$this->_file = $file;
}
public static function getCommonHtml($id=NULL)
{
----
----
}
-----
--- Some other methods---
-----
}
I googled for this & got few solutions but they never worked.
You need to declare your new namespace in your composer.json:
"autoload": {
"psr-4": {
...
"common\\": "common/"
}
},
And the run:
composer dump-autoload
Alternatively you could declare alias for new namespace, so Yii autoloader will handle it (like in advanced template):
Yii::setAlias('#common', dirname(__DIR__))
But Yii autoloader will be dropped in Yii 2.1, so I would stick to composer-way (or do both - alias may be useful not only for autoloading).
I am trying to run PHPUnit_Framework_TestCase on Yii2-advanced. Installed it via composer in folder PHPUnit in the root directory. From there I tried to test with simple test but what I get is an error:
phpunit TestLogin.php
PHP Fatal error: Class 'dektrium\user\models\LoginForm' not found in Z:\toma\toma-metropizza\htdocs\frontend\models\LoginForm.php on line 8
Fatal error: Class 'dektrium\user\models\LoginForm' not found in Z:\toma\toma-metropizza\htdocs\frontend\models\LoginForm.php on line 8
This my TestLogin.php file from the PHPUnit directroy:
<?php
require_once "vendor/autoload.php";
require_once "../frontend/models/LoginForm.php";
class TestLogin extends PHPUnit\Framework\TestCase
{
public function setUp()
{
$login = new LoginForm();
}
public function testStatic()
{
$this->assertClassHasStaticAttribute('test', 'LoginForm');
}
}
This is my LoginForm.php:
<?php
namespace frontend\models;
use Yii;
use \dektrium\user\models\LoginForm as BaseLoginForm;
class LoginForm extends BaseLoginForm
{
public static $test = [];
public function attributeLabels()
{
return [
'login' => Yii::$app->OutData->getLabel(208),
'password' => Yii::$app->OutData->getLabel(98),
'rememberMe' => Yii::t('app','app.Remember me'),
];
}
}
It extends the base dektrium user model. But it seems like the test can't find the base model or something. Can you give me advice? I don't want to use the Yii2 build in tests. Want to write my own. Thank you in advance!
EDIT Directroy structure:
app/
/frontned
/models
LoginForm.php
/PHPUnit
/vendor
composer.json
conposer.lock
TestLogin.php
/vendor
etc.
I created a service provider named AdminServiceProvider
namespace App\Providers;
use Modules\Orders\Models\Orders;
use Illuminate\Support\ServiceProvider;
use View;
class AdminServiceProvider extends ServiceProvider
{
public function boot()
{
$comments = Orders::get_new_comments();
View::share('comments', $comments);
}
public function register()
{
}
}
Registered the provider
App\Providers\AdminServiceProvider::class,
Now I try to attach it to the controller
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Providers\AdminServiceProvider;
class AdminController extends Controller
{
public $lang;
public function __construct()
{
}
public function index(){
return view('admin/dashboard');
}
}
Now I get this error message
Undefined variable: comments
This is the first time I try to use a custom service provider and don't know exactly how it works I'm sure there's something missing Hope you can help. Thanks in advance.
[UPDATE]
removed use App\Providers\AdminServiceProvider; from the controller
php artisan clear-compiled solved the problem but I want to attach it to some controllers not all controllers as the $comments are sent to all contollers in my app. So how to attach the service provider to specific controllers not all of them?
For the undefined variable run: php artisan clear-compiled will solve it
If you want to share a variable in some of your views you can create a middleware and assign it to the views you want to share the data with:
First create a middleware: php artisan make:middleware someName
Then in the handle function you add your view sharing logic:
$comments = Orders::get_new_comments();
view()->share('comments',$comments);
return $next($request);
Then register your middleware under the $routeMiddleware array and
give it an alias.
Then attach it to your routes like:
Route::group(['middleware'=> 'yourMiddlewwareName'], function(){
//your routes
});
If you have all your admin views in one directory (views\admin for example) you can use view composer in AdminServiceProvider:
public function boot()
{
view()->composer('admin.*', function($view){
$view->with('comments', Orders::get_new_comments());
});
}
It will attach comments variable to each view in your views\admin directory.
You can also attach a variable to some specific views or folders like this:
view()->composer(['admin.posts.*', 'admin.pages.index'], function($view){
$view->with('comments', Orders::get_new_comments());
});
I want to use this php library with namespaced classes in my Symfony 1.4 project: https://github.com/donquixote/cellbrush.
I'm not quite familiar with the namespaces concept. So when i fisrt try the to use the main class of this library, according to its docs, i just did:
$table = \Donquixote\Cellbrush\Table\Table::create();
And i got this fatal error:
Fatal error: Class 'Donquixote\Cellbrush\Table\Table' not found in D:\SF_ROOT_DIR\apps\frontend\modules\home\actions\actions.class.php
So i searched for a solution, and supposedly there is one: stackoverflow sol 1, stackoverflow sol 1 eg, but when i try to implement it i still get the above error.
My case:
Directories and files of interest:
D:\SF_ROOT_DIR\lib\autoload\sfClassLoader.class.php
D:\SF_ROOT_DIR\lib\vendor\ClassLoader (contains:
https://github.com/symfony/ClassLoader/tree/2.6)
D:\SF_ROOT_DIR\lib\vendor\cellbrush-1.0 (contains:
https://github.com/donquixote/cellbrush.)
Code:
SF_ROOT_DIR/config/ProjectConfiguration.class.php
require_once dirname(__FILE__).'/../lib/vendor/symfony/lib/autoload/sfCoreAutoload.class.php';
require_once dirname(__FILE__) . '/../lib/autoload/sfClassLoader.class.php';
use Symfony\Component\ClassLoader\UniversalClassLoader;
use Symfony\Component\ClassLoader\ApcUniversalClassLoader;
sfCoreAutoload::register();
class ProjectConfiguration extends sfProjectConfiguration
{
public function setup()
{
$this->namespacesClassLoader();
$this->enableAllPluginsExcept('sfPropelPlugin');
}
public function namespacesClassLoader() {
if (extension_loaded('apc')) {
$loader = new ApcUniversalClassLoader('S2A');
} else {
$loader = new UniversalClassLoader();
}
$loader->registerNamespaces(array(
'Donquixote' => __DIR__ . '/../lib/vendor/cellbrush-1.0/src/Table'));
$loader->register();
}
}
actions.class.php
$table = \Donquixote\Cellbrush\Table\Table::create();
Thanks.
Use composer and its autoloading.
Execute:
composer require donquixote/cellbrush
Now the library is installed in vendor directory and autoloader is generated, you just need to include it. Add this line to the top of config/ProjectConfiguration.class.php:
require_once dirname(__FILE__).'/../vendor/autoload.php';
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.