📜 ⬆️ ⬇️

Extend the Imagick class

Greetings to all my first readers!

Outset


To write this very first article I was pushed by just one single bug in the Imagick library, which took me some time.

It all started with the fact that there was a task to write a certain class in php for working with images. I decided to resort to using ImageMagick and to expanding Imagick.
The Imagick class itself has an extensive number of methods, but it was necessary to expand it and add its own methods, such as checking the existence of the image cache and getting the path to it, the actual caching itself and some other auxiliary ones.
')
For these purposes, a simple class was written:
<?php namespace app; class Images extends \Imagick { private $_filePath = null; private $_cacheFile = null; //   public function readImage($filePath) { $this->_filePath = $filePath; parent::readImage($this->_filePath); } // -   public function myMethod() { } //    ... ?> 


Now let's see why this class will NOT work.

Climax


The reason for the inoperability of this code is that a member of this class "_filePath", like any other, will be NULL. This is bug â„–59565

The problem turned out to be decisive, because without using my own variables, my class lost all meaning.

Decoupling


It is required to solve this problem in such a way as to preserve all the functionality, flexibility and, when a stable release of Imagick is achieved, it would be possible to switch to the “right path” with minimal interference in the code

For this, it occurred to me to use the __call magic method, which is called when the called method of our class is not found. As a result, the class was as follows:

 <?php namespace app; class Images { private $_filePath = null; private $_cacheFile = null; private $_Imagick = null; public function __construct() { $this->_Imagick = new \Imagick(); } //   public function readImage($filePath) { $this->_filePath = $filePath; $this->_Imagick->readImage($this->_filePath); } // -   public function myMethod() { } // ,    public function __call($name, $args) { return call_user_func_array(array($this->_Imagick, $name), $args); } //    ... ?> 

findings


I agree that the solution method is some kind of crutch, but in this situation it is most suitable.
After a stable release, in the class it will be enough to add "extends \ Imagick" and remove the methods of "__call"
and constructor.
PECL Imagick - for today, version 3.0.1 is the latest stable. In version "3.1.0b1" the bug is already fixed. In addition, there is already "3.1.0RC1". However, when the stable version comes out is not yet known.

I will be glad to hear those who have already met with this problem and their solutions.

Source: https://habr.com/ru/post/138179/


All Articles