How to import/use static class with namespace - cakephp

I have been at this for a couple days now. Seems like the simplest thing in the world but for the life of me I cannot get this to work.
I am trying to use this class in my Controller:
https://github.com/neitanod/forceutf8
The class is named Encoding.php and it has a namespace ForceUTF8.
I've tried all of the following:
App::uses('Encoding','Vendor'); //(copying Encoding.php directly in the Vendor dir)
App::uses('Encoding','Vendor/ForceUTF8'); //(copying Encoding.php in ForceUTF8 subdir)
App::uses('Encoding’,’Lib'); //(copying Encoding.php directly in the Lib dir)
App::uses('Encoding’,’Lib/ForceUTF8'); //(copying Encoding.php in ForceUTF8 subdir)
require_once(APP . 'Vendor' . DS . 'Encoding.php'); //(use plain old php require_once to load class from Vendor dir)
No matter what I do I get the same error: Class 'Encoding' not found.
I find the CakePHP documentation to be very confusing on this subject. On the one hand it says not to use App::uses for non-CakePHP classes because the classes might not follow CakePHP standards. Fair enough. So instead they say to use App::import. But then there are tons of posts saying that App::import is nothing more than a wrapper for require_once.
So after not being able to get App::uses or App::import to work, I tried require_once. Same error. Then I found a post here on so saying even when using require_once, you still have to 'initialize' the class in order to CakePHP to be able to see/use it. And how is that done? App::uses. So I'm back where I started.
Something tells me the namespace is causing the problem. When I use require_once the class is found (I'm pretty sure) because, for example, if I change
require_once(APP . 'Vendor' . DS . 'Encoding.php');
to
require_once(APP . 'Vendor' . DS . 'blabla.php');
it gives me an error, file not found.
But even though require_once seems to find it, CakePHP still says class not found.
How can I load a namespaced vendor file?

In Cakephp 2.x, follow following steps
at top of class file add
use \Dropbox as dbx;
[Dropbox is vendor directory in my case]
use \Dropbox as dbx;
App::build(array('Vendor/Dropbox' => array('%s' . 'Dropbox' . DS)), App::REGISTER);
// Autoload the classes in the 'vendors'
spl_autoload_register(function ($class) {
foreach (App::path('Vendor') as $base) {
$path = $base . str_replace('\\', DS, $class) . '.php';
if (file_exists($path)) {
include $path;
return;
}
}
});
Now call your class method.

Cake2.x does not support namespaces so you need write your own loader
spl_autoload_register(function ($class) {
foreach (App::path('Vendor') as $base) {
$path = $base . str_replace('\\', DS, $class) . '.php';
if (file_exists($path)) {
include $path;
return;
}
}
});
more info here:
http://www.dereuromark.de/2012/08/06/namespaces-in-vendor-files-and-cake2-x/

Base on this article:
http://www.dereuromark.de/2012/08/06/namespaces-in-vendor-files-and-cake2-x/comment-page-1
I'm using the paypal sdk. And this is my code.
In bootstrap.php:
// Add 'vendors' as sub-package of 'Vendor' to the application
App::build(array('Vendor/vendors' => array('%s' . 'vendors' . DS)), App::REGISTER);
// Autoload the classes in the 'vendors'
spl_autoload_register(function ($class) {
foreach (App::path('Vendor/vendors') as $base) {
$path = $base . str_replace('\\', DS, $class) . '.php';
if (file_exists($path)) {
include $path;
return;
}
}
});
In the PaypalComponent:
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
Use those classes in function:
$this->apiContext = new ApiContext(
new OAuthTokenCredential()
);

Related

Load vendor assets from custom directory - cakephp 3

I want to create vendor package in cakephp 3. It should depend on another package, that has both php files and some static assets: like js, css, img etc. Setting up php files autoloading I am able to handle. However to load static files from another vendor, e.g.
echo $this->Html->css('AnotherPackage.styles');
cake expects that they should be inside vendor's webroot directory, which they are not
# another package's files
/vendor/author/another-package/php
/vendor/author/another-package/css_files
/vendor/author/another-package/js_files
/vendor/author/another-package/images
Only similar issue I found is copying files to webroot , which is something I do not want to do.
How can I tell cake to load the vendor's files from their exact folders instead of webroot ? Or in what better way this problem can be solved, without being have to copy something. I am using composer.
Thanks
Are you doing this on a Linux box? If so, you could just create a symbolic link in order to have the webroot directory point right back at the root directory of the package.
Are you using composer?
Does the project you're working on depend on the vendor's package within your composer.json file?
If so, you could create a Controller (something like ExternalAssets) in your project that can read those vendors files, and pass them through to the Response object.
<?php
/**
* ExternalAssetsController
*/
namespace App\Controller;
use App\Controller\Controller\AppController;
use Cake\Core\App;
use Cake\Http\Exception\BadRequestException;
use Cake\Http\Exception\ForbiddenException;
use Cake\Routing\Router;
/**
* ExternalAssets Controller
*
* Serves up external assets that aren't in the webroot folder.
*/
class ExternalAssetsController extends AppController
{
/**
* Initialize method.
*
* #return void
*/
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
// see https://book.cakephp.org/3.0/en/development/routing.html#routing-file-extensions
// or whatever extensions you need.
Router::extensions(['css', 'js', 'png', 'jpg']);
// if you're using the auth component in a restricted way.
$authAllowedActions = ['asset'];
$this->Auth->allow($authAllowedActions);
}
/**
* Delivers an asset.
*
* #param string|null $folder The Folder's name.
* #param string|null $file The File's name.
* #return \Cake\Http\Response
* #throws \Cake\Http\Exception\BadRequestException When $folder or $file isn't set.
* #throws \Cake\Http\Exception\ForbiddenException When we can't read the file.
*/
public function asset($folder = null, $file = null)
{
if (!$folder) {
throw new BadRequestException(__('Folder was not defined'));
}
if (!$file) {
throw new BadRequestException(__('File was not defined'));
}
$folder = str_replace('..', '', $folder);
$file = str_replace('..', '', $file);
$basepath = realpath(ROOT . DS . 'vendor' . DS . 'author' . DS . 'another-package');
$path = realpath(ROOT . DS . 'vendor' . DS . 'author' . DS . 'another-package' . DS . $folder . DS . $file . '.' . $this->getRequest()->getParam('_ext'));
if (strpos($path, $basepath) === false) {
throw new ForbiddenException(__('Path out of bounds, possible hack attempt.'));
}
if (!is_readable($path)) {
throw new ForbiddenException(__('Unable to read the file.'));
}
$this->setResponse($this->getResponse()->withFile($path, [
'name' => $file . '.' . $this->getRequest()->getParam('_ext'),
'download' => false
]));
return $this->getResponse();
}
}
Then use Router::url() to create the compiled path to your controller.
Something like:
<link rel="stylesheet" href="<?=Router::url([
'prefix' => false,
'plugin' => false, // unless the controller in in a plugin
'controller' => 'ExternalAssets'
'action' => 'asset'
0 => 'css_files',
1 => 'css_file_name',
'_ext' => 'css'
]) ?>">

cakephp get realpath of view and layout

How can i retrieve absolute path of view and layout file in cakephp action.
I cant find useful method or property in
// in action
var_dump($this);
Thank
desire out put is
/home/sweb/www/cakeapp/app/View/Layout/mylayout.ctp
/home/sweb/www/cakeapp/app/View/Mycntl/myaction.ctp
I would use this to create a full path.
APP . 'View' . DS . 'Layout' . DS . $this->layout
Which will output something like this for you,
string '/Users/david/Sites/ExampleSite/app/View/Layout/default' (length=56)
In order to get the view, I'd use
APP . 'View' . DS . $this->modelClass . DS . $this->view

What has happened to javascript helper in cakePHP 2?

I have used this item and get this error :
Missing Helper
Error: JavascriptHelper could not be found.
Error: Create the class JavascriptHelper below in file: app/View/Helper/JavascriptHelper.php
<?php
class JavascriptHelper extends AppHelper {
}
Well indeed, this file does not exists, and I tried to use 'Js' in my helper array.
class myClassController expend AppController {
var $helpers = array('Html', 'Js'); // and not 'Javascript');
In the code, the method $this->Javascript->codeBlock is called to add a javascript method (in the middle of the content instead of the header) but there is no $this->Js->codeBlockcodeBlock either.
$output .= $this->Js->codeBlock("datepick('" . $htmlAttributes['id'] . "','01/01/" . $options['minYear'] . "','31/12/" . $options['maxYear'] . "');");
Could you explain me what happened to the old Javascript helper or how to get the code working?
Is there an other helper which could work with CakePHP-2.0?
Cordially,
Have you read the migration guide? If not do that now:
http://book.cakephp.org/2.0/en/appendices/2-0-migration-guide.html#xmlhelper-ajaxhelper-and-javascripthelper-removed
XmlHelper, AjaxHelper and JavascriptHelper removed The AjaxHelper and
JavascriptHelper have been removed as they were deprecated in version
1.3. The XmlHelper was removed, as it was made obsolete and redundant with the improvements to Xml. The Xml class should be used to replace
previous usage of XmlHelper.
The AjaxHelper, and JavascriptHelper are replaced with the JsHelper
and HtmlHelper.
JsHelper JsBaseEngineHelper is now abstract, you will need to
implement all the methods that previously generated errors.
So
$this->Js->codeBlock('...');
is now
$this->Html->codeBlock('...');
HtmlHelper::scriptBlock($code, $options = array())
//Parameters:
$code (string) – The code to go in the script tag.
$options (array) – An array of html attributes.

Autoload a namespaced (PSR-0) directory of classes in CakePHP?

I'm trying to import Assetic (https://github.com/kriswallsmith/assetic) classes.
Managed to do the ugly :
App::import('Vendor', 'LessphpFilter', array('file' => 'assetic' . DS . 'src' . DS . 'Assetic' . DS . 'Filter' . DS . 'LessphpFilter.php'));
But it crashes on a sub-required file.
Any idea how to do achieve this in a clean way?
I had similar issues a couple of weeks ago and haven't found a really clean/satisfying way to do this. But I managed to solve problems with sub-required files by adding paths to the include path before the import. Like so:
$pathExtra = APP.'Vendor'.DS.PATH_SEPARATOR.APP.'Vendor'.DS.'pear'.DS;
$path = ini_get('include_path');
$path = $pathExtra . PATH_SEPARATOR . $path;
ini_set('include_path', $path);
App::import('Vendor', 'consumer', array('file' => 'Auth'.DS.'OpenID'.DS.'Consumer.php'));

CakePHP generate and save PDF

I am using CakePHP for an application that does auto generation of vouchers to a PDF file. But they work through user clicks. Now I wish to create it automatically and have the file written to the server hard disk. Then later on, these files will get zipped up and sent to an email of my choice.
For the PDFs I use Html2ps/Html2pdf component found in CakePHP. You can view it here http://bakery.cakephp.org/articles/Casmo/2010/06/26/creating-pdf-files-with-html2ps-html2pdf
One issue I have is the formatting doesn't look right. If I have links that look like this:
http://www.mydomain.com/this-is-my-perma-link
They will render this way in the generated PDF:
http://www.mydomain.com/this- is- my- perma- link
And that would be a broken link. I've tried to use other characters to replace the dash but it doesn't work. I am not sure why.
Another issue is, how can I write the generated PDF file to my server hard disk? Is there an option for me to do that and how do I define the destination. Any examples?
Maybe thanks in advance!
Hi you can to use FPDF library . and you can to save file in the server and then redirect to other function.
check the next code.
///Call to library
<?php
App::uses('AppController', 'Controller');
require_once APP . 'Vendor' . DS . 'fpdf17' . DS . 'fpdf.php';
class TestController extends AppController {
public function test(){
--Create fpdf.
$pdf = new FPDF();
$pdf->AddPage();
$pdf->Output('files/Report.pdf');
$pdf->text($x,$y,'Txt');
return $this->redirect(
array('controller' => 'Test', 'action' => 'test_new')
);
}
}

Resources