Want to create a custom function

不羁的心 提交于 2019-12-08 10:40:23

问题


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.

For example this function

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 ...

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


回答1:


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

etc

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

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




回答2:


Create this function in your AppContoller.php like

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

Call this in any controller like

$str = "anything";
$your_output = $this->__replaceDashes($str);

OR

You can make your own component.



来源:https://stackoverflow.com/questions/17448380/want-to-create-a-custom-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!