How can i use Symfony or Zend Components inside Code Igniter? - php

I would like if there is a simple and clean way to use ZF´s (or Symfony´s) component library in a CodeIgniter application, because there is a lot of good and useful stuff there that CI don´t have.

It´s possible. For example for ZF, you would need to do something like:
1) Setup CodeIgniter.
2) Download the Zend Framework. Extract the archive.
3) From the ZF files, copy the “Zend” directory from inside the “library” directory.
4) Paste the directory into the “system/application/libraries” directory.
So ultimately, the new location of the copied “Zend” directory would be “system/application/libraries/Zend”.
If you’re on Linux/Unix, we probalby will need to deal with file permissions.
I guess you will need to make the Zend directory accessible by all (use chmod).
5) In the same “system/application/libraries/” directory, create a new file named “Zend.php” and put the following contents:
<?php if (!defined('BASEPATH')) {exit('No direct script access allowed');}
class Zend
{
function __construct()
{
ini_set('include_path',
ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries');
}
function load($class)
{
require_once (string) $class . EXT;
}
}
?>
Now test the setup using the CI´s default Welcome controller
<?php
class Welcome extends Controller {
function Welcome()
{
parent::Controller();
}
function index()
{
$this->load->library('zend');
$this->zend->load('Zend/Service/Flickr');
$flickr = new Zend_Service_Flickr('12e99caebb8f305fff5a943606ecde18');
$results = $flickr->tagSearch('worldcup');
foreach ($results as $result)
{
$photo = $result->Small;
echo "<img src=\"{$photo->uri}\" /><br /><br />";
}
}
}
?>

You can use components symfony by installing them via composer.
For example, you can install the varDumper component which provides a better dump() function that you can use instead of var_dump.
composer require symfony/var-dumper
the composer will install the dumper component with all his dependecy
then include the autoload and use the dump function
require __DIR__.'/vendor/autoload.php';
// create a variable, which could be anything!
$someVar = ...;
dump($someVar);

Related

Mapping home controller as the default controller in AltoRouter

This is the index.php
<?php
include 'library/altorouter.php';
$router = new AltoRouter();
$router->setBasePath('/AltoRouter');
$router->map('GET','/', 'home_controller#index', 'home');
$router->map('GET','/content/[:parent]/?[:child]?', 'content_controller#display_item', 'content');
$match = $router->match();
// not sure if code after this comment is the best way to handle matched routes
list( $controller, $action ) = explode( '#', $match['target'] );
if ( is_callable(array($controller, $action)) ) {
$obj = new $controller();
var_dump($obj);
call_user_func_array(array($obj,$action), array($match['params']));
} else if ($match['target']==''){
echo 'Error: no route was matched';
} else {
echo 'Error: can not call '.$controller.'#'.$action;
}
// content_controller class file is autoloaded
class home_controller {
public function index() {
echo 'hi from home';
}
}
and it works good. The home_controller class is supposed to be the default controller.
Problem is, when I remove the class home_controller
class home_controller {
public function index() {
echo 'hi from home';
}
}
and save it as a seprate file home_controller.php in app/controller directroy it does not work.
I understand that the router is unable to locate the home_controller class hence will not show it's content (if i directly include the file home_controller.php it again works as normal).
My question is, how do you map the home_controller as default, which is in a different directory?
It looks like you're not using composer for installing the package. It's standard way in PHP.
1. Install Composer
Here is manual, depending on your OS
2. Call Composer from Command Line
Go to your root directory of your project, open Command Line and type:
composer require altorouter/altorouter
You'll find the package name altorouter/altorouter in composer.json on Github page of package - here.
3. Add loaded files to your index.php
Now you have installed router package. Next step is adding all composer loaded files to your application. Just replace include 'library/altorouter.php'; with following:
<?php
# index.php
require_once __DIR__ . '/vendor/autoload.php';
4. Load Your Controllers by Composer as well
Last step is tell composer where to find your classes.
Open composer.json and add following section:
{
"autolaod": {
"classmap": ["app"]
}
}
Read more about classmap option in documentation.
To update /vendor/autoload.php with this option, just call from command line:
composer dump-autoload
That should be it. If you come at any troubles, let me know which point.

Undefined method with Composer library and CodeIgniter

I'm working on a project and it's getting a little too hard for me...
I explain.
I need to parse PDF files with PHP, to analyse the content of those files. To do that, I use pdfparser.org library.
I firstly tried to include this library as usually, without any result.
After having read all the Internet, since this library requires Composer to be installed (and on my web hosting I can't get Composer installed), I have applied the Composer process on my Windows PC. I got the "vendor" folder with the "autoload.php" file. Fine !!
Then, I have tried to include it properly in CodeIgniter. The solution I chose is :
Creating a file "Pdfparser.php" in application/libraries/
class Pdfparser
{
public function __construct()
{
require_once APPPATH."/third_party/pdfparser.php";
}
}
Then, I add the PdfParser "Composer" application in application/third_party/, and in the /third_party/pdfparser.php I simply put :
if (!defined('pdfparser')) {
define('pdfparser', dirname(__FILE__) . '/');
require(pdfparser . 'pdfparser/autoload.php');
}
Then, I add this library to CodeIgniter /application/config/autoload.php as :
$autoload['libraries'] = array('pagination', 'form_validation','email','upload','pdfparser');
Finally, I call it in my function in application/controllers/Admin.php :
$parser = new Pdfparser();
$pdf = $parser->parseFile(myfile.pdf);
$full_text = $pdf->getText();
(This 4. block of code is directly taken from official Documentation here : http://www.pdfparser.org/documentation, and just adapted).
But now, I break the Internet... I have this error :
PHP Fatal error: Call to undefined method PdfParser::parseFile() in /path/application/controllers/Admin.php on line 3083
After having looked CodeIgniter documentation, I try to add the Composer autoloader to the core... in application/config/autoload.php I put :
$config['composer_autoload'] = APPPATH . "/third_party/pdfparser/autoload.php";
Of course, it doest not work. And I'm lost...
Use composer properly. $config['composer_autoload'] = TRUE; and inside your application folder run composer install smalot/pdfparser . Then inside your controller it should run, if not use Use :)
use Smalot\PdfParser;
class My_controller extends CI_Controller {
}
When using composer, to include a library in your project you do something like that :
composer install smalot/pdfparser
Then, to include the newly installed library, you only need to include the "autoload.php" file provided by composer :
<?php
include 'vendor/autoload.php';
$parser = new Pdfparser();
$pdf = $parser->parseFile(myfile.pdf);
$full_text = $pdf->getText();
var_dump($full_text);
Nothing more.
Replace your code
class Pdfparser
{
public function __construct()
{
require_once APPPATH."/third_party/pdfparser.php";
}
}
with
<?php
require_once APPPATH."/third_party/pdfparser.php";
class Pdfparser
{
public function __construct()
{
}
}
Include outside of your class.
Rather than using autoloading you can load library like this...
$this->load->library('library_name');
Example:
$this->load->library('pdfparser');

Laravel start function not calling from inside a namespace

So I'm writing a Laravel 4 app and I've setup namespaces. I'm just trying to write some systemwide functionality that I can execute from anywhere mainly to create menus/setup language/currencies etc.
I have directory to global called "library" which has currently a file called Menu.php inside it which looks as follows:
<?php
namespace Library;
use AppName\Model\Menu as MenuModel;
class Menu {
public static function BuildMenu($id = 1) {
//retrieve menu
$menu = MenuModel::GetMenu($id);
//sort content for page
$data = $menu->toArray();
print_r($data);
}
}
I am currently attempting to call the BuildMenu function in the filters.php file with the following:
App::before(function($request)
{
//
View::share('Menu', Library\Menu::BuildMenu());
});
I get a class 'Library\Menu' not found error from laravel. I'm presuming this is something to do with my lack of knowledge of namespaces so any clarity would be appreciated.
Did you add your library path to composer.json ?
if not, just add it to autoload > classmap >> app/library
and run artisan dump-autoload
should be fine.

Will a directory with a period break autoload resolution based on a namespace in Zend Framework?

I have a folder in my library folder which is named after my website. The folder path is like:
~\www\library\myWebsite.com
If I'm using Zend autoloader to load the namespace of everything in the library path, will I have any trouble autoloading a class from that file with a namespace like this:
\myWebsite.com\myClass::myFunction();
I have looked online for documentation on this and I can't find any info about using periods in this way.
I tried it and the complication is in PHP. I think Zend is registering the namespace fine, because when I call \Zend_Load_Autoloader::getRegisteredNamespaces() it shows that it's registered. but when I call the static method from the fully qualified namespace, php gives an error of this:
Fatal error: Undefined constant 'myWebsite' in /home/jesse/www/application/controllers/MyController.php on line 15
It seems like PHP is terminating the namespace identifier, during parsing, at the . (period character). This is dissapointing because to me having a library named after the website was important to my design.
I will rename the directory to myWebsitecom or possibly make the .com it's own sub directory like
myWebsite\com and incorporate that into my namespace tree like: \MyNamespace\Com\MyClass::myFunction();
The easiest way to find out is to try it.
If it doesn't work, you could always write a custom autoloader to make it work. I don't have much experience with php namespaces, but the autoloader would look something like this (I imagine you'll have to tinker with it a bit to determine the correct file path given the class name):
<?php
class My_Loader_Autoloader_MyWebsite implements Zend_Loader_Autoloader_Interface {
/**
* (non-PHPdoc)
* #see Zend_Loader_Autoloader_Interface::autoload()
*/
public function autoload($class) {
if (strtolower(substr($class, 0, 9)) == 'mywebsite') {
$file = realpath(APPLICATION_PATH . '/../library/myWebsite.com/' . $class);
if ($file) {
require_once $file;
return $class;
}
}
return false;
}
}
then put this in your bootstrap:
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->pushAutoloader(new My_Loader_Autoloader_MyWebsite());
and if this class must be in that myWebsite.com directory, you could just cheat and throw in a require in there too:
require_once(APPLICATION_PATH . '/../library/myWebsite.com/Loader/Autoloader/MyWebsite.php');

Include HTMLpurifier with Zend_Loader

I want to use the HTMLpurifier in combination with the Zend Framework. I would love to load the Class and its files with the Zend_Loader. How would you include it? Would you just use the HTMLPurifier.auto.php or do you know a better way of doing it?
I use HTML Purifier as a filter in my Zend Framework project. Here's an altered version of my class:
require_once 'HTMLPurifier.includes.php';
require_once 'HTMLPurifier.autoload.php';
class My_Filter_HtmlPurifier implements Zend_Filter_Interface
{
protected $_htmlPurifier = null;
public function __construct($options = null)
{
// set up configuration
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.DefinitionID', 'My Filter');
$config->set('HTML.DefinitionRev', 1); // increment when configuration changes
// $config->set('Cache.DefinitionImpl', null); // comment out after finalizing the config
// Doctype
$config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
// configure caching
$cachePath = APPLICATION_PATH . '/../cache/htmlpurifier';
if (!is_dir($cachePath)) {
mkdir($cachePath, 0755, true);
}
$cachePath = realpath($cachePath);
$config->set('Cache.SerializerPath', $cachePath);
if (!is_null($options)) {
//$config = HTMLPurifier_Config::createDefault();
foreach ($options as $option) {
$config->set($option[0], $option[1], $option[2]);
}
}
$this->_htmlPurifier = new HTMLPurifier($config);
}
public function filter($value)
{
return $this->_htmlPurifier->purify($value);
}
}
Unless I'm misunderstanding the question (Or HTMLpurifier). If you have Zend_Loader running and it's set to autoload.
require_once('Zend/Loader.php');
Zend_Loader::registerAutoload();
Or something to that effect. Put the HTMLpurifier class in your library directory. I'm just not sure on it's actual class name.
You can just put the class file in the library directory and call it by it's name, or maybe toss it in a misc package.
Examples
// SITE/library/Zend/Auth.php
class Zend_Auth
{
}
// SITE/library/htmlpurifier.php
class htmlpurifier
{
}
// SITE/library/misc/htmlpurifier.php
class Misc_HTMLpurifier
{
}
Make sense?
you can register an autoloader class using the Zend_Loader class. when you call the registerAutoLoad() method without any parameters, you are actually registering Zend_Loader itself as an autoloader. so:
Zend_Loader::registerAutoLoad();
// equals to: Zend_Loader::registerAutoLoad('Zend_Loader'),true);
Zend_Loader tries to load classes using Zend Framework's naming convention, which is like this:
each class is defined in a separate file
each class name begins with a capitalized letter
underlines in class name, means a directory level.
so if 'Zend_Loader' is the name of a class, it is defined in the file 'Loader.php' in 'Zend' directory in your path. to you PHP can file load this class from file Zend/Loader.php
if your classes follow this naming convention, they can be automatically loaded using the same autoloader. else, you need to define your own autoloader. write an autoloader class winch can extend Zend_Loader, and define the loading functionality so that it will load classes with other naming conventions. then register your own autoloader with Zend_Loader. like this:
Zend_Loader::registerAutoLoad('myLoader',true);
I've put the contents of library of the archive of HTMLPurifier in my library path. So I have this directory structure :
library/
HTMLPurifier\
HTMLPurifier.auto.php
...
HTMLPurifier.safe-includes.php
And then I put this on top of the file where I'm using the HTMLPurifier :
require_once 'HTMLPurifier.safe-includes.php';
Ugly, but it's working.

Categories