【问题标题】:PHP: Detecting when a variables value has been changedPHP:检测变量值何时更改
【发布时间】:2013-05-16 22:46:58
【问题描述】:

我想知道是否有一种方法可以将更改侦听器之类的内容添加到变量中。我的意思最简单的例子就是按照这些思路工作;

// Start with a variable
$variable = "some value";

// Define a listener
function myChangeListener($variable) {
    // encode with json_encode and send in cookie
}

// Add my listener to the variable
addListenerToVariable(&$variable, 'myChangeListener');

// Change the variables value, triggering my listener
$variable = "new value";

现在您可能会问,为什么我什至需要费心使用这种方法,为什么不创建一个函数来设置 cookie。答案是我有一个&__get($var) 魔术方法,它返回对多维数组元素的引用,我希望使用类似的方法来检测何时/是否编辑了数组元素或其子元素之一,然后发送一个cookie(如果有)。希望的结果会像这样工作;

$cookies->testArray["test"] = "newValue";
// This would send the cookie 'testArray' with the value '{"test":"newValue"}'

老实说,我认为这是完全不可能的,如果我是正确的,我深表歉意。但是我昨天才学会了如何正确使用引用,所以我想在我完全写下这个想法之前先问问。

感谢我收到的任何回复,无论是我希望的还是我期望的。

编辑:

为了更清楚起见,这里是我想要完成的示例类;

class MyCookies {
    private $cookies = array();
    private $cookieTag = "MyTag";

    public function __construct() {
        foreach($_COOKIE as $cookie => $value) {
            if(strlen($cookie)>strlen($this->cookieTag."_")&&substr($cookie,0,strlen($this->cookieTag."_"))==$this->cookieTag."_") {
                $cookieVar = substr($cookie,strlen($this->cookieTag."_"));
                $this->cookies[$cookieVar]['value'] = json_decode($value);
            }
        }
    }

    // This works great for $cookies->testArray = array("testKey" => "testValue");
    // but never gets called when you do $cookies->testArray['testKey'] = "testValue";
    public function __set($var, $value) {
        if(isset($value)) {
            $this->cookies[$var]['value'] = $value;
            setcookie($this->cookieTag.'_'.$var,json_encode($value),(isset($this->cookies[$var]['expires'])?$this->cookies[$var]['expires']:(time()+2592000)),'/','');
        } else {
            unset($this->cookies[$var]);
            setcookie($this->cookieTag.'_'.$var,'',(time()-(172800)),'/','');
        }
        return $value;
    }

    // This gets called when you do $cookies->testArray['testKey'] = "testValue";
    public function &__get($var) {
        // I want to add a variable change listener here, that gets triggered
        // when the references value has been changed.

        // addListener(&$this->config[$var]['value'], array(&$this, 'changeListener'));

        return $this->config[$var]['value'];
    }

    /*
    public function changeListener(&$reference) {
        // scan $this->cookies, find the variable that $reference is the reference to (don't know how to do that ether)
        // send cookie
    }
    */

    public function __isset($var) {
        return isset($this->cookies[$var]);
    }

    public function __unset($var) {
        unset($this->cookies[$var]);
        setcookie($this->cookieTag.'_'.$var,'',(time()-(172800)),'/','');
    }

    public function setCookieExpire($var, $value, $expire=null) {
        if(!isset($expire)) {
            $expire = $value;
            $value = null;
        }
        if($expire<time()) $expire = time() + $expire;
        if(isset($value)) $this->cookies[$var]['value'] = $value;
        $this->cookies[$var]['expires'] = $expire;
        setcookie($this->cookieTag.'_'.$var,json_encode((isset($value)?$value:(isset($this->cookies[$var]['value'])?$this->cookies[$var]['value']:''))),$expire,'/','');
    }
}

至于我为什么不想有更新功能,真的只是个人喜好。这将在其他人可以扩展的框架中使用,我认为让他们能够将 cookie 视为单行代码中的变量感觉更流畅。

【问题讨论】:

  • 我认为这在 php.ini 中是不可能的。对于实现 SplObserver 接口的自定义类,可能是一种选择,但您必须在进行更改时通知。
  • 我不明白你的魔法 get 方法与此有什么关系。此外,您的第二个代码示例似乎与您的第一个代码示例没有太大关系。我认为更好的代码示例会为我澄清事情。我只是扔一些东西,希望它朝着正确的方向发展:__set()?!这样您也可以看到变量何时更改。但是,一旦我真正知道您想要什么,我将能够提供更好的帮助。 PHP 确实为 Listeners 提供了一些功能。
  • @MichaSchwab 我用示例类更新了我的问题。

标签: php variables reference listener magic-methods


【解决方案1】:

如果你想在数组或其他任何东西中实现自己的事件处理程序/触发器,那么你可以使用类包装器。

对于一个变量,正如您所注意到的,__get()__set() 魔术方法就足够了。 对于数组,有一个更好的处理程序:ArrayAccess。它允许使用类方法和常见的数组语义来模拟数组动作(如其他一些语言中的 collections)。

<?php
header('Content-Type: text/plain');

// ArrayAccess for Array events
class TriggerableArray implements ArrayAccess {
    protected $array;      // container for elements
    protected $triggers;   // callables to actions

    public function __construct(){
        $this->array    = array();

        // predefined actions, which are availible for this class:
        $this->triggers = array(
            'get'    => null,     // when get element value
            'set'    => null,     // when set existing element's value
            'add'    => null,     // when add new element
            'exists' => null,     // when check element with isset()
            'unset'  => null      // when remove element with unset()
        );
    }

    public function __destruct(){
        unset($this->array, $this->triggers);
    }

    public function offsetGet($offset){
        $result = isset($this->array[$offset]) ? $this->array[$offset] : null;

        // fire "get" trigger
        $this->trigger('get', $offset, $result);

        return $result;
    }

    public function offsetSet($offset, $value){
        // if no offset provided
        if(is_null($offset)){
            // fire "add" trigger
            $this->trigger('add', $offset, $value);

            // add element
            $this->array[] = $value;
        } else {
            // if offset exists, then it is changing, else it is new offset
            $trigger = isset($this->array[$offset]) ? 'set' : 'add';

            // fire trigger ("set" or "add")
            $this->trigger($trigger, $offset, $value);

            // add or change element
            $this->array[$offset] = $value;
        }
    }

    public function offsetExists($offset){
        // fire "exists" trigger
        $this->trigger('exists', $offset);

        // return value
        return isset($this->array[$offset]);
    }

    public function offsetUnset($offset){
        // fire "unset" trigger
        $this->trigger('unset', $offset);

        // unset element
        unset($this->array[$offset]);
    }

    public function addTrigger($trigger, $handler){
        // if action is not availible and not proper handler provided then quit
        if(!(array_key_exists($trigger, $this->triggers) && is_callable($handler)))return false;

        // assign new trigger
        $this->triggers[$trigger] = $handler;

        return true;
    }

    public function removeTrigger($trigger){
        // if wrong trigger name provided then quit
        if(!array_key_exists($trigger, $this->triggers))return false;

        // remove trigger
        $this->triggers[$trigger] = null;

        return true;
    }

    // call trigger method:
    // first arg  - trigger name
    // other args - trigger arguments
    protected function trigger(){
        // if no args supplied then quit
        if(!func_num_args())return false;

        // here is supplied args
        $arguments  = func_get_args();

        // extract trigger name
        $trigger    = array_shift($arguments);

        // if trigger handler was assigned then fire it or quit
        return is_callable($this->triggers[$trigger]) ? call_user_func_array($this->triggers[$trigger], $arguments) : false;
    }
}

function check_trigger(){
    print_r(func_get_args());
    print_r(PHP_EOL);
}

function check_add(){
    print_r('"add" trigger'. PHP_EOL);
    call_user_func_array('check_trigger', func_get_args());
}

function check_get(){
    print_r('"get" trigger'. PHP_EOL);
    call_user_func_array('check_trigger', func_get_args());
}

function check_set(){
    print_r('"set" trigger'. PHP_EOL);
    call_user_func_array('check_trigger', func_get_args());
}

function check_exists(){
    print_r('"exists" trigger'. PHP_EOL);
    call_user_func_array('check_trigger', func_get_args());
}

function check_unset(){
    print_r('"unset" trigger'. PHP_EOL);
    call_user_func_array('check_trigger', func_get_args());
}

$victim = new TriggerableArray();

$victim->addTrigger('get', 'check_get');
$victim->addTrigger('set', 'check_set');
$victim->addTrigger('add', 'check_add');
$victim->addTrigger('exists', 'check_exists');
$victim->addTrigger('unset', 'check_unset');

$victim['check'] = 'a';
$victim['check'] = 'b';

$result = $victim['check'];

isset($victim['check']);
unset($victim['check']);

var_dump($result);
?>

演出:

"add" trigger
Array
(
    [0] => check
    [1] => a
)

"set" trigger
Array
(
    [0] => check
    [1] => b
)

"get" trigger
Array
(
    [0] => check
    [1] => b
)

"exists" trigger
Array
(
    [0] => check
)

"unset" trigger
Array
(
    [0] => check
)

string(1) "b"

我假设,您可以使用 数组引用参数 修改此代码中的构造函数,以便能够在那里传递超全局数组,例如 $_COOKIE。另一种方法是直接在课堂内将$this-&gt;array 替换为$_COOKIE。此外,还有一种方法可以用anonymous functions 替换可调用对象。

【讨论】:

  • 正要发布同样的内容 :-) +1!
【解决方案2】:

根本不改变变量怎么样。

仅通过可以处理您想要执行的任何“侦听”任务的函数(或类方法)访问变量怎么样?

为什么必须这样做:$variable = 5;

什么时候可以:setMyVariable(5)

function setMyVariable($new_value) {
  $variable = $new_value;
  // do other stuff

}

【讨论】:

    【解决方案3】:

    我认为你的想法有一些错误,因为他们唯一可以改变 php 中变量值的方法是 改变它。因此,当您更改变量时,请运行您的代码。

    如果您需要一种通用的方法来执行此操作,我建议将数组或其值封装到一个类中。但是确实没有充分的理由不能在每次值更改后运行 sendCookie()。

    我认为更改侦听器适用于多线程编程。

    【讨论】:

    • “你的想法有误”? OP 可能会编译自己的 PHP 扩展,这可能允许这样做。没有错误。
    • 有人从未听说过观察者模式。
    • 确实没听说过。
    • @CORRUPT - 你是在嘲笑我还是在嘲笑 OP?
    • PHP 中的“观察者模式” - 听起来它违反了 PHP 的 Keep it Simple Stupid 原则......简而言之,对于一个愚蠢的人来说,OP 的优势是什么?
    猜你喜欢
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 2011-10-29
    • 2016-02-24
    • 2013-07-06
    相关资源
    最近更新 更多