duanliaolan6178 2015-12-15 20:21
浏览 22
已采纳

PHP关联数组:值的唯一函数

So due to some nasty framework issues, I'm a little stuck here. Basically, I'm taking a string from user input, and replacing it with a value from my model that is only known at call time.

My structures are like so:

static public $placeholders = array("[REPLACE_STRING_1]"=>'firstName',
                                    "[REPLACE_STRING_2]"=>'DateTime->format(\'aa,bb\')');
//Problem line above.  Very messy, format is an arm long and painful

public function myfunction(ModelClass $master) {
    $body = $this->sampleService->get('samplebody'); // populate body from DB
    foreach(static::$placeholders as $key => $value){
        $body = str_replace($key, $master->value, $body);
    }
    return $body;
}

So this makes for some very ugly code. My boss would like to edit it to make for a function to be part of the array, assigned to each entry, that would run to filter/edit the code. Something like

function dateFormat($prop){
    return $prop->format('aa,bb');
}
function asIs($prop){
    return $prop;
}

static public $placeholders = array("[REPLACE_STRING_1]"=>['firstName', asIs]
                                    "[REPLACE_STRING_2]"=>['DateTime', dateFormat]);

Are there any existing structures or functions in PHP which make this possible, or is his code desire just a pipedream?

EDIT: I figured out a solution very similar to the answer posted below, but with a few modifications necessary to pass along variables.

function dateFormat ($prop, $master) {
    return $master->$prop->format('aabb');
}
function asIs ($prop, $master) {
    return $appointment->$prop;
}
static public $placeholders = array("[REPLACE_STRING_1]"=>['firstname','asIs'], 
                                    "[REPLACE_STRING_2]"=>['DateTime', dateFormat];

//instatiate service to get sampleService values

//main difference here
public function buildBody(ModelClass $master) {
    $body = $this->sampleService->get('samplebody');
    foreach(static::$placeholders as $key => $value){
        $body = preg_replace_callback('/'.preg_quote($key).'/',
        //Use closure here to pass in $master, otherwise laravel gets angry about strings instead of objects
        function ($matches) use ($master) {
            $placeholder = static::placeholders[$matches[0]];
            $func = $placeholder[1];
            $prop = $placeholder[0];
            return call_user_func(array($this, $func), $prop, $appointment);
        }, $body);
    }
    return $body;
}

All in all this was a very interesting problem for me, and I'm trying to find a way to clean it up even further. Going to mark your answer as correct, since it greatly helped get here.

  • 写回答

1条回答 默认 最新

  • duanqiao8925 2015-12-16 13:17
    关注

    If I got the question right, I'd go with preg_replace_callback and do it somewhat like this:

    function dateFormat($prop){
        return $prop;
    }
    
    function asIs($prop){
        return $prop;
    }
    
    static public $placeholders = array(
        "[REPLACE_STRING_1]"=>['firstName', 'asIs'],
        "[REPLACE_STRING_2]"=>['DateTime', 'dateFormat']
    );
    
    private function replace($matches) {
        $placeholder = static::$placeholders[$matches[0]];
        $func = $placeholder[1];
        $prop = $placeholder[0];
    
        // this calls your class methods ('asIs', 'dateFormat')
        // with $prop = 'firstName' etc.
        return call_user_func(array($this, $func), $prop);
    }
    
    public function myfunction(ModelClass $master) {
        $body = $this->sampleService->get('samplebody');
    
        foreach(static::$placeholders as $key => $value) {
            // use a callback replace method instead of str_replace
            $body = preg_replace_callback('/' . preg_quote($key) . '/', array($this, 'replace'), $body);
        }
    
        return $body;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)