• 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I instantiate a custom class based helper in a view

#1
I have inherited a site based on the CI framework.

There is a custom helper 'imageresize_helper.php' built as a class with constructor rather than just functions:

Class ImageResize
{
   
   private $fileName;

   /**
   * @param string $fileName
   */
   function __construct($fileName)
   {
       $fileName = base_path($fileName);
   }


...

public function resizeImage($newWidth, $newHeight, $option = 'auto')
   {

}

The helper is referenced in autoload.php 
$autoload['helper'] = [
   'imageresize',
]   


How do I load & instantiate the helper class and call the resize function in a view?

Thanks

SeanR
Reply

#2
Where is the file that defines Class ImageResize located?
Reply

#3
in /application/helpers/imageresizer_helper.php
Reply

#4
In the world of CodeIgniter Helpers are not written in an Object Oriented format. In other words, they are not classes.
The code you have is a library.

You should move the file to /application/libraries/ and rename it as shown making sure the first character in the file name is uppercase, ie.  Imageresize.php

Change the class definition from
PHP Code:
Class ImageResize 
to
PHP Code:
Class Imageresize 

The CamelCase naming won't work well with CodeIgniter. (Keep the uppercase first letter.)

Remove this from /config/autoload.php
PHP Code:
$autoload['helper'] = ['imageresize'];   

It looks like the class requires a file name when it is instantiated. The code you share does not show any other method. Without some other way to supply the file name, this class is not a good candidate for use with $autoload. The reason is that that way of loading resources doesn't accommodate arguments to the autoload request.

If the class has some other way to set what file it's working with you could use the following in /config/autoload.php
PHP Code:
$autoload['libraries'] = ['imageresize'];   

If you don't want it to autoload (a.k.a. always load) but only in specific places use
PHP Code:
$this->load->library('imageresize''filename'); 

Either way, the class file will be included and an object instantiated and ready for use.

PHP Code:
$this->imageresize->resizeImage($newWidth$newHeight); 
Reply

#5
Hi Dave, that explains why I couldn't find any docs showing helpers as objects rather than functions! Also explains why the library was never instantiated anywhere in code.

I'll follow your guidance to move into libraries.

Many thanks
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.