How can I use my own external class in CakePHP 3.0?

Jon Lachmann picture Jon Lachmann · Feb 14, 2015 · Viewed 13.2k times · Source

I am creating an application in CakePHP 3.0, in this application I want to draw SVG graphs of data using a php class that I have written. What would be the proper way to go about using this class in my CakePHP 3 project?

More specifically:

  • What are the naming conventions? Do I need to use a specific namespace?

  • Where do I put the file that contains the PHP class?

  • How can I include it and use it in a controller or a view?

Answer

Fazal Mohammad picture Fazal Mohammad · Feb 15, 2015

What are the naming conventions? Do I need to use a specific namespace?

Your SVG graphs class should have a namespaces. For namespaces you can see http://php.net/manual/en/language.namespaces.rationale.php

Where do I put the file that contains the PHP class?

  1. Create a folder by author(here might be your name, as you are the author) in vendor

  2. Then create your class inside of it convention is vendor/$author/$package . You can read more http://book.cakephp.org/3.0/en/core-libraries/app.html#loading-vendor-files

How can I include it and use it in a controller or a view?

a) To include:

require_once(ROOT .DS. 'Vendor' . DS . 'MyClass' . DS . 'MyClass.php');

(replace MyClass by your foldername and MyClass.php by your filename.php)

b) To use it:

add use MyClass\MyClass; in your controller

For example I want to add MyClass in a controller. Steps that worked for me

  1. Creating vendor\MyClass folder
  2. Pasting MyClass.php in that folder
  3. adding namespace MyClass; at the top of MyClass.php

MyClass.php have following code for example:

namespace MyClass;


class MyClass
{
    public $prop1 = "I'm a class property!";

    public function setProperty($newval)
    {
        $this->prop1 = $newval;
    }

    public function getProperty()
    {
        return $this->prop1 . "<br />";
    }
}
  1. Adding use MyClass\MyClass; at the top of controller

  2. Then including it in my controller action. My action sample

       public function test()
     {
         require_once(ROOT .DS. "Vendor" . DS  . "MyClass" . DS . "MyClass.php");
    
         $obj = new MyClass;
         $obj2 = new MyClass;
    
         echo $obj->getProperty();
         echo $obj2->getProperty();
         exit;
     }