Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 MyClassMyClass; in your controller

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

  1. Creating vendorMyClass 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 MyClassMyClass; 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;
     }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...