How to implement Imagine image library in Codeigniter - php

I am trying to add the Imagine image library into a Codeigniter application, but this is the first time I have ever encounter the "namespace" and "use" concept which I just don't get. Most Libs usually need an include, require etc... to make them work with your framework but I am having a hard time trying to implement this "namespace", "use" approach.
Now how far did I get, well I downloaded the Lib, put the Imagine folder in my libraries folder in CI where I have another image Lib call wideimage which I had no problem adapting to CI. I try to be creative and and loaded the library files just like any regular library file is loaded in CI.
And thats where the problem began, I started getting a lot of errors like class is not found got the error line and right away I thought it may need that other file that has that class now that work for some of the errors that it kept on giving me but its like every time a new lib file is loaded another error comes up and some errors just won't go away even if the file with the main class is present.
Now I did found an article on how to set an SPL auto load and I got the following code
set_include_path('/application/libraries/Imagine' . PATH_SEPARATOR . get_include_path());
function imagineLoader($class) {
$path = $class;
$path = str_replace('\\', DIRECTORY_SEPARATOR, $path) . '.php';
if (file_exists($path)) {
include $path;
}
}
spl_autoload_register('\imagineLoader');
But never got it to work, in this case it gave me an error of CI classes or files where not being found.
Now again to my questions is there a way to implemet this Imagine image library into Codeigniter?
To either load it through the regular library loader or through an autoload file?
Something like this;
class Test extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('imagine');
}
public function index()
{
// Do some cool things with the image lib functions
}
}
Well I would really appreciate anyone's help on this in the mean time I will keep on looking around the web to see if I can find an answer.

Anyway after a day of looking I finally found a way to do it, and thank you simplepie feed parser I knew I had seen similar code in the past.
Anyway I actually looked over at the simplepie autoloader.php file which loads the classes to use simplepie and I just did some small adjustments to the code to be able to use Imagine Lib in Codeigniter.
So here are the steps and code:
1 download the Imagine Library at:
https://github.com/avalanche123/Imagine
2 Copy the Imagine folder into your CI application libraries folder: application/libraries
3 Create a file and call it imagine_autoload.php
4 add the following code to the imagine_autoload.php file
set_include_path('/application/libraries/Imagine' . PATH_SEPARATOR . get_include_path());
function imagineLoader($class) {
$path = $class;
$path = str_replace('\\', DIRECTORY_SEPARATOR, $path) . '.php';
if (strpos($class, 'Imagine') !== 0)
{
return;
}
include_once $path;
}
spl_autoload_register('\imagineLoader');
Now to the fun part on your controller do the following:
require_once('./application/libraries/imagine_autoloader.php');
// Here you can use the imagine imagine tools
use Imagine\Image\Box;
use Imagine\Image\Point;
class Testing extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index($offset = 0)
{
$imagine = new \Imagine\Gd\Imagine();
$image = $imagine->open('/path/to/image.jpg');
$thumbnail = $image->thumbnail(new Imagine\Image\Box(100, 100));
$thumbnail->save('/path/to/thumnail_image.jpg');
}
}
Now go an look at where you saved the new image and you will find a new image that has been re size.
Hopefully someone will find this useful.

Related

PHP & Composer: Runtime check if class is autoloadable

Recently I decided to upgrade some projects from my own (...) autoloader solution to a Composer PSR-4 autoloader. My code already followed PSR-4 so, no big deal there.
On a specific case, I had the following code:
public static function isAutoLoadable($className)
{
$className = ltrim($className, "\\");
$file = $GLOBALS["Path"] . "/src/" . str_replace("\\", "/", $className) . ".php";
if (false !== stream_resolve_include_path($file))
return $file;
return false;
}
It allowed me to check whatever a given class name could be loaded, without actually trying to load it and result on a PHP Class * not found error.
Use case:
I'm currently using it to replace controllers that by some reason couldn't be found with a generic error one, avoiding an App crash and just telling the user something went wrong... then extra internal logging is done.
A function would be good since I can call it before trying to load a controller... I don't want this behavior to spread to any other classes on the app
So my question is: Is there a equivalent way to check if Composer is able to autoload some class without forcing it to load it and cause an error? -- So I can take further actions in case the class wasn't found?

Classes/PHPExcel_Shared_String.php): failed to open stream

This question was asked in 2010. I am seeing a related problem but the recommended solutions from 2010 don't fix it.
I am using PHPExcel v 1.8.0 (March 2014)
The suggestions made on the original reply have been incorporated and the rest of the system still works normally, for example I have an init.php file that is brought in for every scrip which includes the following as suggested in an earlier post:
function myAutoload($Class)
{
require_once 'Classes/' . $Class . '.php';
}
spl_autoload_register('myAutoLoad')
All {classes.php} files are in the Classes/ folder off the document root including, of course PHPExcel.php. The PHPExcel folder is also contained in the Classes/ folder.
I have tried various ways of spinning up PHPExcel, including the usual
$spreadsheet = new PHPExcel;
As an alternative I also tried defining a Spreadsheet class
Class Spreadsheet extends PHPExcel {.... }
They all produce the same error as cut and paste into the above
I have successfully ported over the remainder of the processes in the application from a procedural style to object orientated system, and it has been well worth the weeks that have been spent on it. This last hurdle with PHPExcel however has got me foxed!
Any suggestions would be appreciated
Modify your autoloader to return a false if it can't load the specified file:
function myAutoload($Class)
{
if (file_exists('Classes/' . $Class . '.php')) {
require_once 'Classes/' . $Class . '.php';
return true;
}
return false;
}
That way, autoloading will from through your own autoloader and execute the next autoloader in the "queue" (the PHPExcel autoloader) if it doesn't find the requested file through your own autoloader. If you don't return a false the SPL autoloader handler won't bother working through any other "queued" autoloaders

avoid redeclaring an interface for more one time

I have an interface which I named Manager, and two classes UtilisateurManager and StageManager, and the both of them implements the Manager interface.
In each class I included the interface Manager as the following :
require '../helpers/Manager.class.php';
Then I needed to use these two classes at once in a php script, but I got the error that I can't redeclare class Manager.
I tried to work with the function class_exists() but it's not useful in my case.
How can I solve this problem ?
Maybe you can use require_once instead of require.
require_once '../helpers/Manager.class.php';
You need to implement a simple autoloader which will try to load class/interface only if it isn't already loaded, and forget about direct require/include then. It is considered good practice to leave the filesystem details out of the class file: you may reuse it in other project where your directories system might change, so you'll need to edit the class again.
A simple example:
class Autoloader
{
protected $directories = array();
public function register()
{
// register 'loadClass' method as an autoloader
spl_autoload_register(array($this, 'loadClass'));
}
public function addSource($dir)
{
$this->directories[] = $dir;
}
public function loadClass($className)
{
foreach ($this->directories as $dir) { // search in every registered sources root
$fileName = $dir.DIRECTORY_SEPARATOR.$className.'.class.php';
if (file_exists($fileName) {
include($fileName);
return; // halt when file was found
}
}
}
}
// bootstrap file
$autoloader = new Autoloader;
$autoloader->register();
(spl_autoload_register documentation)
Please note that this realization will cycle through the folders, and this is certainly not the desired solution. The best option today is to build project according to PSR-4 spec - autoloader implementation will have to check existence of a single file only. It may be a little hard to dive into namespaces without any preparation, but once you get familiar with this coding style, you will forget about direct file load.
The last thing, i want to warn you about your naming convention - your Interface is stored in a .class.php file, and this is confusing.

How to implement a class using namespaces in PHP

I am having trouble implementing a particular class in PHP. I want to use Anthony Ferrara's RandomLib library in my Zend Framework application (you can find it here.)
I've been programming in PHP for a few years now, so I know my way around it for the most part. But I have to admit that I'm kind of clueless when it comes to using classes that implement namespaces. Here's what I've got in my code:
public static function generateToken()
{
require_once 'RandomLib/Factory.php';
$factory = new \RandomLib\Factory;
$generator = $factory->getMediumStrengthGenerator();
return $generator->generate(16);
}
Unfortunately, I'm getting the following error:
Fatal error: Class 'SecurityLib\AbstractFactory' not found in C:\xampp\php\includes\RandomLib\Factory.php on line 30
Like I said, I really have no idea what's going on here. I don't know if I'm supposed to use some kind of use statement in my class or not.
With autoloader with ZF 1.*, asuming you put your factoru into application_name/libs/RandomLibFactory.php as RandomLibFactory class it should look like this:
public static function generateToken() {
$factory = $locator = new RandomLibFactory();
$generator = $factory->getMediumStrengthGenerator();
return $generator->generate(16); }
For anyone whom spent lot of time and didn't find a clue, tearing his hairs apart and hitting the wall to death:
you need to have an autoloader as in "bootstrap.php" in the folder "test/", to manage every namespace... or you need to link every file in the folder which is not very smart. See spl_autoload_register in php.net
you just downloaded RandomLib, which depends on another library (the author didn't mentioned it): so you need SecurityLib (it has the same folder structure: copy what is inside "lib/" into the other "lib/" folder.
example of autoloader for a script calling from the root folder "RandomLib-1.1.0/" (see that 'lib' in the $path ?):
spl_autoload_register(function ($class) {
$nslen = strlen(__NAMESPACE__);
if (substr($class, 0, $nslen) != __NAMESPACE__) {
//Only autoload libraries from this package
return;
}
$path = substr(str_replace('\\', '/', $class), $nslen);
$path = __DIR__ . '/lib/' . $path . '.php';
if (file_exists($path)) {
require_once $path;
}
});
now you are set and can use classes freely without worrying about including or requiring files.
$factory = new RandomLib\Factory;
$generator = $factory->getLowStrengthGenerator();
//$generator = $factory->getMediumStrengthGenerator();
//$generator = $factory->getHighStrengthGenerator();
$randomStringLength = 16;
$randomStringAlphabet = '0123456789#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/';
$randomString = '';
for ($i=0;$i<10;$i++){
$randomString = $generator->generateString( $randomStringLength , $randomStringAlphabet);
echo $randomString.'<br>';
}
I too tore out many hairs, before I found the solution for my Windows machine.
I downloaded the Windows version of Composer (which I had barely heard of let alone used).
I used it to install RandomLib (as shown in the Install section of the instructions - use a command box in Windows)
This generated a vendor folder containing a composer folder an ircmaxell folder and an autoload.php file; these I uploaded to a suitable place in my website The vendor directory includes both the random-lib and the - required - security-lib libraries.
In the program in which I wanted to generate random text I included that autoload.php (preceded by suitable directory pointers)
Then I was good to go to create a factory, generator and string as shown in the library's instructions

php cannot redeclare _autoload()

I getting more indepth with php and I am creating my own mini mvc framework to learn OOP.
I have a .htaccess file that redirects everything to the index.php. In the index.php I include a file called boootstrap.php to parse the url and load the class php file.
Now that I am adding ActiveRecord http://www.phpactiverecord.org to add database access. I get the error:
Fatal error: Cannot redeclare class AutoLoader in /home/i554246/public_html/mvc/lib/Autoloader.php on line 4
I am not sure how to stop the conflict.
index.php:
include(MVC_CORE_INCLUDE_PATH . DS . 'Bootstrap.php')
include(MVC_CORE_INCLUDE_PATH . DS . 'activerecord/ActiveRecord.php');
autoloader.php which is included in bootstrap.php
<?php
class AutoLoader
{
public static function Load($Class)
{
$File = BASEDIR.$Class.'.php';
if(is_readable($File))
{
require($File);
}
else
{
die('Requested module "'.$Class.'" is missing. Execution stopped.');
}
}
}
spl_autoload_register('AutoLoader::Load');
ActiveRecord.php
if (!defined('PHP_ACTIVERECORD_AUTOLOAD_DISABLE'))
spl_autoload_register('activerecord_autoload',false,PHP_ACTIVERECORD_AUTOLOAD_PREPEND);
function activerecord_autoload($class_name)
{
$path = ActiveRecord\Config::instance()->get_model_directory();
$root = realpath(isset($path) ? $path : '.');
if (($namespaces = ActiveRecord\get_namespaces($class_name)))
{
$class_name = array_pop($namespaces);
$directories = array();
foreach ($namespaces as $directory)
$directories[] = $directory;
$root .= DIRECTORY_SEPARATOR . implode($directories, DIRECTORY_SEPARATOR);
}
$file = "$root/$class_name.php";
if (file_exists($file))
require $file;
}
?>
Perhaps change
if (file_exists($file))
require $file;
to
if (file_exists($file))
require_once($file);
You either try to include a file twice (you might want to use require_once) or you have 2 classes (one from a library you use?) with that same name.
if There seem to be 2 classes called AutoLoader, you might want to look into namespaces. I can't recall phpactiverecord having a class called that, but as you might use several libraries you were bound to run into this.
The best way would be to put your own autoloader class in a namespace. Make sure you keep all your calls correct, so calls to the autoloader should have \yournamespace\ in front of it, and calls inside the autoloader might need prepending a \ to (like \Exception for instance)
PHP-ActiveRecord doesn't have any AutoLoader class. What happens here I guess, is that you have two loaders that are loading the file.
Since it's PSR-0 compliant, you can load it using your own loading utility (assuming it's embracing that convention). If you do so just disable PHP-AR autoloading utility.
define('PHP_ACTIVERECORD_AUTOLOAD_DISABLE', true);
The vanilla loader is moslty useful for finding model classes which won't be needed if you're putting them in their own namespace. As your framework might not follow PHP-AR convention regarding where the models are, it seems correct to disable that autoloader.
Check that example of PHP-AR integration with lithium framework: li3_activerecord
I moved the line
$Bootstrap = new Bootstrap();
under the
include(MVC_CORE_INCLUDE_PATH . DS . 'Bootstrap.php');
include(MVC_CORE_INCLUDE_PATH . DS . 'Controller.php');
but above
require_once 'lib/activerecord/ActiveRecord.php'; the ActiveRecord seemed to want to load it again

Categories