如何在 CakePHP 3.0 中使用我自己的外部类? [英] How can I use my own external class in CakePHP 3.0?

查看:23
本文介绍了如何在 CakePHP 3.0 中使用我自己的外部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 CakePHP 3.0 创建一个应用程序,在这个应用程序中,我想使用我编写的 php 类绘制数据的 SVG 图形.在我的 CakePHP 3 项目中使用这个类的正确方法是什么?

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?

更具体地说:

  • 命名约定是什么?我需要使用特定的命名空间吗?

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

我把包含 PHP 类的文件放在哪里?

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?

推荐答案

什么是命名约定?我需要使用特定的命名空间吗?

您的 SVG 图形类应该有一个命名空间.对于命名空间,您可以查看 http://php.net/manual/en/language.namespaces.rationale.php

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

将包含 PHP 类的文件放在哪里?

  1. 在 vendor 中按作者创建一个文件夹(这里可能是你的名字,因为你是作者)

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

然后在里面创建你的类约定是 vendor/$author/$package .你可以阅读更多http://book.cakephp.org/3.0/en/core-libraries/app.html#loading-vendor-files

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

如何包含它并在控制器或视图中使用它?

a) 包括:

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

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

(用你的文件夹名替换 MyClass,用你的文件名.php 替换 MyClass.php)

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

b) 使用它:

在控制器中添加 use MyClassMyClass;

例如我想在控制器中添加 MyClass.对我有用的步骤

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

  1. 正在创建 vendorMyClass 文件夹
  2. 将 MyClass.php 粘贴到该文件夹​​中
  3. 在 MyClass.php 的顶部添加 namespace MyClass;

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. 在控制器顶部添加use MyClassMyClass;

然后将其包含在我的控制器操作中.我的行动样本

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;
 }

这篇关于如何在 CakePHP 3.0 中使用我自己的外部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆