duanputian5341 2013-12-19 02:11
浏览 40

如何在php中获取给定函数的名称?

tl;dr: I need to get the name of a given function, but not the current function I'm in.

For example, something like the "getFunctionName()" in the code bellow:

$listFieldNames = array(
    getFunctionName($country->getName()) => 'Name',
    getFunctionName($country->getAcronym()) => 'Acronym'
);

You may be wondering why do I want to do this. Well, I came up with that when I was thinking about how to handle user input in my app. After reading a lot of discussions about using or not using exceptions to validate user input, I ended up choosing to use something like a Notification class (I'm using Zend Framework 1.12):

class Application_Model_Notification
{
    protected $message;
    protected $fieldName;
    protected $code;

    public function __construct($message, $fieldName = NULL, $code = NULL)
    {
        return $this->setMessage($message)
            ->setFieldName($fieldName)
            ->setCode($code);
    }

    // getters and setters;
}

When I validate the data sent by the user, for each field that has a bad input, I push a notification into an array. Each notification use the $fieldName attribute to identify what field is holding the problematic information.

This way, I can show to the user the fields with bad input and place messages near their matching fields. Because the attributes in Model can have different names from the UI forms names (specially when the webdesigner and the webdeveloper aren't the same person), I need to build a list matching them. And here is the problem: I want to avoid build that list with plain strings. The reason is I can change the name of an attribute in the Model, and it would be painfull to change it in the lists too. Otherwise, if a I use the name of its getter, I could easily change it by using the refactor command of the IDE. I just don't know how to get it! And it's not by using the magic constants, because they only work with the current function/method, while my case is about any method given...

I don't know if what I'm doing is a good practice, so I'm putting bellow what I intend to do:

In the Country Controller

public function insertAction()
{
    $country = new Application_Model_Country();
    $country->setName($this->getParam('Name'))
        ->setAcronym($this->getParam('Acronym'));

    $bloCountry = new Application_Model_Business_Country();
    try {
        // The aforementioned list
        $listFieldNames = array(
            getFunctionName($country->getName()) => 'Name',
            getFunctionName($country->getAcronym()) => 'Acronym'
        );

        $bloCountry->insert($country, $listFieldNames);
        if ($bloCountry->countNotifications() > 0) {
            $this->view->notifications = $bloCountry->getNotifications();
        } else {
            $this->view->success = 'Country saved succesfuly.';
        }
    } catch (Exception $e) {
        $this->view->error = $e->getMessage();
    }
}

In the Country Business Object inside the Model

protected $_country;
protected $_notifications;

// Constructor, getters, setters and other methods
// (...)

protected function validate($country, $listFieldNames)
{
    if (trim($country->getName()) == '') {
        $_notifications[] = new Application_Model_Notification(
            'The country name must be specified',
            $listFieldNames[getFunctionName($country->getName())]
        );
    } else {
        $_country->setName(trim($country->getName()));
    }
}

public function insert($country, $listFieldNames)
{
    $this->validate($country, $listFieldNames);
    if (countNotifications() > 0) {
        return 0;
    } else {
        $daoCountry = new Application_Model_DbTables_Country();
        return $daoCountry->save($this->_country);
    }
}

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongli8862 2013-12-19 03:16
    关注

    So for each custom field that comes from the web, you're going to want a validation function that gets called on it. You can do this on the model level. You're going to have to define those yourself; you will have to do some work.

    Defining an interface provides a contract that each model must not break. That means that you can expect every class/model that implements it to have those functions defined.

    interface FieldValidationInterface
    {
        public function isValid();
        public function getNotifications();
    }
    
    class Country implements FieldValidationInterface
    {
        /**
         * Check to see if the model is valid 
         * by checking every field
         */
        public function isValid()
        {
            $valid = true;
    
            // go through each private member
            if (!$this->name) {
                $this->notifications['name'] = 
                    'The country name must be specified';
                $valid = false;
            }
    
            return $valid;
        }
    
        public function getNotifications()
        {
            return $this->notifications;
        }
    }
    
    // The logic for insertAction()
    if (!$coutry->isValid()) {
        foreach ($country->getNotifications() as $field => $msg) {
            // do something to report to the web: 
            // which field was bad ($field), and why ($msg)
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏