CakePHP 自定义全局函数 [英] CakePHP Custom Global Function

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

问题描述

我正在处理的应用程序有几个名为active"的数据库字段,它是布尔值.但是,与其在视图中显示1"或0",我希望它说是"或否".

The application I am working on have several database fields called "active", which is boolean. However, instead of displaying "1" or "0" in views, I would like it to say "Yes" or "No".

我有以下功能:

function activeFriendlyName($status)
    {
        if ($status == 1)
        {
            return "Yes";
        }
        else
        {
            return "No";
        }
    }

但是,我不确定应该把这个全局函数放在哪里?会是 app_model.php 文件吗?另外,我如何调用这个函数来应用格式化"?

However, I am unsure where I should put this global function? Would it be the app_model.php file? In addition, how would I call this function to apply the "formatting"?

推荐答案

在需要显示之前,您应该保持来自数据库的数据不变.这意味着 View 是更改它的正确位置.我只想做一个简单的:

You should leave the data coming from the database as is until you need to display it. That means the View is the right place to change it. I'd just go with a simple:

echo $model['Model']['bool'] ? "Yes" : "No";

但是,如果您需要更复杂的格式规则并且不想每次都重复,请制作自定义 Helper.

But if you need more complex formating rules that you don't want to repeat every time, make a custom Helper.

可以bootstrap.php中定义一个全局函数,但我不推荐它.

You could define a global function in bootstrap.php, but I wouldn't recommend it.

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

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