Include helper class in view - yii2

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

Related

How to add assetbundle js/css add only in one page in yii2?

I have added fullcalendar js/css in vendor/bower folder. I want to add this into just one page.
I read abt AssestBundle on this link - http://www.yiiframework.com/doc-2.0/guide-structure-assets.html
But this add in all the pages.
In Yii 2 framework asset bundles is recommended way of working with js / css. It's not limited to just adding to all pages. You can use it only in specific view.
Example of asset bundle for JsTree plugin:
<?php
namespace backend\assets;
use yii\web\AssetBundle;
class JsTreeAsset extends AssetBundle
{
public $sourcePath = '#bower_components/jstree/dist';
public $js = [
'jstree.min.js',
];
public $css = [
'themes/default/style.min.css',
];
public $depends = [
'yii\web\JqueryAsset',
];
}
In this example, #bower_components alias is used, in order to get it working you also need to register it in application bootstrap file (in advanced application template this file is common/config/bootstrap.php):
Yii::setAlias('bower_components', dirname(dirname(__DIR__)) . '/bower_components');
Then, in view where you need to use it, call register() method of this asset bundle and pass current view:
use backend\assets\JsTreeAsset;
...
JsTreeAsset::register($this);
The files in default asset bundle (AppAsset) which included in application templates are loaded in every view because it's registered in application layout and layout is applied to all views.

I can't use Autoloader from Symfony2 in Symfony 1.4 for load this namespaced classes

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

PHP namespace behaviour gives FATAL error with spl_autoload_register

I want to use namespace and spl_autoload_register together but failed with different error each time.
Please See complete code files on github.
Below are the files
a base file where create a class with namespace class.alpha.php
an include file where I define spl_autoload_register include.php
an example file which instantiate the class object eg.php
Now when I create object from eg.php it gives FATAL error but when I comment namespace line in class.alpha.php then it's working
Please see the code below.
alpha.class.php
<?php
//namespace Alpha; //<< comment and uncomment this to regenerate the error
class Alpha
{
// public static $baseDir_;
public $dir = __DIR__;
public static $baseDir_;
public function __construct()
{
echo __FILE__."=>".__METHOD__;
var_dump(self::$baseDir_, $this->dir);
$firstDir = !empty(self::$baseDir_) ? self::$baseDir_ : $this->dir;
}
}
include.php
<?php //namespace Alpha\config;
spl_autoload_extensions(".php");
spl_autoload_register('loadclass');
function loadclass($class)
{
try {
if (is_readable(strtolower($class).".class.php")) {
include_once strtolower($class).".class.php";
}
} catch (Exception $e) {
print "Exception:". $e;
}
}
//#link http://php.net/manual/en/function.spl-autoload-register.php
// spl_autoload_register(__NAMESPACE__.'Alpha\Alpha()' );
eg.php
<?php
require_once 'include.php';
/** below code works by commenting 1st line on alpha.class.php
if we un comment then below code gives Fatal error: Class 'Alpha' not found */
Alpha::$baseDir_ = '/opt/lampp/archive/';
$obj_ = new Alpha();
var_dump(get_included_files());
var_dump($obj_);
/** now we define namespace Alpha on alpha.class.php */
// $ns_ = new Alpha\Alpha(); // Fatal error: Class 'Alpha\Alpha' not found
// var_dump($ns_);
/** not working even with use statement */
// use Alpha;
// use Alpha;
// $fn = new Alpha\Alpha();
// var_dump($fn);
Please help me out to solve this issue.
Thanks
Your autoloader is receiving a request for a class of "Alpha\Alpha" if you uncomment the namespace in alpha.class.php and place the use Alpha\Alpha in eg. This means that the location it's expecting to find your class in would be alpha\alpha.class.php.
Unless you're on Windows, directory separators are typically forward slash (/). So there's a number of possible solutions.
**Possible Solution #1 - Leave all files in the same place **
If you want to leave everything where it is now, you'll need to remove the namespace from the class names in the autoloader. If you add these lines to the top of your autoloader, that will make it behave that way:
$classParts = explode("\\", $class);
$class = $classParts[count($classParts) - 1];
I would not recommend this solution though since it means that you can no longer provide the same class name in a different namespace.
Possible Solution #2 - Put namespaces in subdirectories
For this solution, you'd create a new directory "alpha" and move "alpha.class.php" into it. For autoloader changes, you can add the following lines to the top of your autoloader:
$class = str_replace("\\", "/", $class);
This will change the namespace separators from backslashes to file path separators with forward slash. This will work on windows as well as mac and linux.
Possible Solution #3 - Follow an established autoloading standard
There are already a number of standard PHP autoloading standards. PSR-0 (now deprecated) works, but PSR-4 would be recommended:
PSR-0: http://www.php-fig.org/psr/psr-0/
PSR-4: http://www.php-fig.org/psr/psr-4/
One big upside of following one of these standards is that there are already plenty of implementations for them and there's been a lot of thought put into how they should work and maintain compatibility with other libraries you may end up wanting to use. Composer (http://getcomposer.org) will allow you to set up and use both PSR-0 and PSR-4 style autoloaders based on a very simple configuration.
Anyway, for the TL;DR crowd, the issue is that the autoloader receives the entire namespaced path in order to know how to load the class. The fatal error was because the autoloader wasn't properly mapping from that namespaced class to a file system location, so the file containing the class was never being loaded.
Hope this helps.

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.

Laravel 3: Class not found in namespace

This is the problem: I haven't be able to load a class from a namespace.
I'm developing a restful app and I'm trying to follow the Entity/Service/Repository way to access and give format to the requested data. The thing is that I cannot load any class from Services. I have created a folder inside my app called api, and within it the others 3 folders: api/entities/, api/services/ and api/repositories/. There are 2 more folders inside services: validators and datapickers.
As it is a RESTulf app, I also created an api folder inside the controllers folde: controllers/api/.
Here is the the current tree of my app folder:
app/
api/
entities/
repositories/
services/
datapickers/
MemberData.php
ConsumeData.php
validators/
...
models/
controllers/
api/
members.php
(other restful controllers)
languages/
...
In first instance, this is my Autoload section from start.php:
Autoloader::directories(array(
path('app').'models',
path('app').'libraries',
path('app').'api'
));
Autoloader::namespaces(array(
'Api' => path('app').'api',
));
And this is MemberData.php:
<?php
namespace Api\Services\Datapickers;
use Api\Repositories as Repo;
class MemberData
{
/* Do some stuff */
}
Now, when I try to use MemberData in controllers/api/members.php:
<?php
use Api\Services\Datapickers\MemberData;
class Api_Members_Controller extends Api_Base_Controller
{
public function get_index($id = null)
{
if (!empty($id))
$this->params->data = MemberData::getById($id);
else
{
$this->params->data = MemberData::getAll(
Input::get('offset'),
Input::get('limit')
);
}
return Response::json($this->params, 200);
}
}
I get the following:
Unhandled Exception
Message:
Class 'Api\Services\Datapickers\MemberData' not found
Location:
/path_to_project/application/controllers/api/members.php on line 15
which is this line: $this->params->data = MemberData::getById($id);
I autoload the api folder and register the base api namespace in start.php but I still keep receiving the same error. IT's like Laravel doesn't recognize the api namespace or something like that.
I tried to register the full namespace:
Autoloader::namespaces(array(
'Api\Services\Datapickers' => path('app').'api/services/datapickers',
));
but the error I got was: Call to undefinde method 'Api\Services\Datapickers\MemberData::getById()'. This was just a test (I don't want to register every sub-namespace in the Autoloader).