本文介绍了想要创建自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CakePHP 2.x ..我想创建一个特殊的类,其中我想创建函数,以便我可以从其他控制器调用函数。

I am working on a CakePHP 2.x .. I want to create a special class in which I want to create functions so that I can call functions from other controllers.

例如此函数

function replace_dashes($string) {
   $string = str_replace("-", " ", $string);
  return $string;
     }

所以每当我想在其他控制器中使用该函数时,或者可以传递参数...

So whenever I want to use that function in some other controller I can call this or can pass parameters too ...

我想在一些类中实现所有的原始函数。如何在CakePHP中这样做?

I want to implement all the raw functions like this in some class. How can I do this in CakePHP?

推荐答案

只需在/ Lib中创建一个文件,最好使用Utility这样的命名空间:

Its not that difficult. Just create a file in /Lib, ideally with a namespace like "Utility":

/Lib/Utility/Utility.php

并将您的方法放入其中:

and put your methods in there:

class Utility {
    public static function replaceDashes($string) { ... }
}

然后你可以在你的应用程序的任何地方使用它:

Then you can use it anywhere in your app:

//App::uses('ClassName', 'Package'); and our Package is the Folder "Utility" in /Lib
App::uses('Utility', 'Utility');
$result = Utility::replaceDashes($input);

https://github.com/dereuromark/tools/blob/master/Lib/Utility/Utility.php =nofollow> https://github.com/dereuromark/tools/blob/master/Lib/Utility /Utility.php
及其对于现实生活场景/示例的测试用例。

See https://github.com/dereuromark/tools/blob/master/Lib/Utility/Utility.phpand its test case for a real life scenario/example.

不要忘记写几个测试用例,以及。

Don't forget to write a few test cases for, as well.

这篇关于想要创建自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 13:57