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?
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?
Create a folder by author(here might be your name, as you are the author) in vendor
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
namespace MyClass;
at the top of MyClass.phpMyClass.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 />";
}
}
Adding use MyClass\MyClass;
at the top of controller
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;
}