V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
moell
V2EX  ›  PHP

ArrayAccess 使用详解和实现配置化程序

  •  
  •   moell · 2016-10-30 22:40:57 +08:00 · 1473 次点击
    这是一个创建于 2773 天前的主题,其中的信息可能已经有所发展或是发生改变。

    简介

    ArrayAccess (数组式访问)接口:提供像访问数组一样访问对象的能力的接口。

    提供接口

    ArrayAccess {
        //检查一个偏移位置是否存在
        abstract public boolean offsetExists ( mixed $offset );
    
        //获取一个偏移位置的值
        abstract public mixed offsetGet ( mixed $offset );
    
        //设置一个偏移位置的值
        abstract public void offsetSet ( mixed $offset , mixed $value );
    
        //复位一个偏移位置的值
        abstract public void offsetUnset ( mixed $offset );
    }
    

    如果我们想像数组一样来访问你的 PHP 对象只需要实现 ArrayAccess 接口即可

    实例运用

    场景:假如我有一个 User 类,映射的是用户的信息,想通过数组的方式来访问和设置用户信息

    <?php
    /**
     * Created by PhpStorm.
     * User: moell
     * Date: 16-10-30
     * Time: 下午 8:49
     */
    
    namespace User;
    
    
    class User implements \ArrayAccess
    {
        private $data = [];
    
        public function __construct()
        {
            $this->data =  [
                'name' => 'moell',
                'sex' => '男',
                'email' => '[email protected]'
            ];
        }
    
        /**
         * 检查指定字段数据是否存在
         *
         * @param $offset
         * @return bool
         */
        public function offsetExists($offset)
        {
            return isset($this->data[$offset]);
        }
    
        /**
         * 获取指定字段数据
         *
         * @param $offset
         * @return mixed
         */
        public function offsetGet($offset)
        {
            return $this->data[$offset];
        }
    
        /**
         * 设置指定字段数据
         *
         * @param $offset
         * @param $value
         * @return mixed
         */
        public function offsetSet($offset, $value)
        {
            return $this->data[$offset] = $value;
        }
    
        /**
         * 删除指定字段数据
         *
         * @param $offset
         */
        public function offsetUnset($offset)
        {
            unset($this->data[$offset]);
        }
    }
    
    $user = new User();
    
    //获取用户的 email
    echo $user['email'].PHP_EOL;  // [email protected]
    
    //检查 age 是否存在
    var_dump(isset($user['age'])); // bool(false)
    
    //设置 age
    $user['age'] = 18;
    echo $user['age'].PHP_EOL; //18
    
    //删除 age
    unset($user['age']);
    var_dump(isset($user['age'])); // bool(false)
    
    

    我们的对象可以像数组一样操作了,是不是很神奇呢?


    实现程序配置化

    在我们构建应用中,经常会通过一个配置文件变更程序的一个行为,通过 ArrayAccess 我们会更轻松的实现。

    下面我带你们一起看看我是这么实现的

    1. 在项目更目录下创建一个 config 目录 2. 在 config 目录下创建相应的配置文件,比如 app.php 和 database.php 。文件程序如下

    app.php

    <?php
    
    return [
        'name' => 'app name',
        'version' => 'v1.0.0'
    ];
    

    database.php

    <?php
    
    return [
        'mysql' => [
            'host' => 'localhost',
            'user' => 'root',
            'password' => '12345678'
        ]
    ];
    

    3. Config.php 实现 ArrayAccess

    <?php
    
    namespace Config;
    
    class Config implements \ArrayAccess
    {
        private $config = [];
    
        private static $instance;
    
        private $path;
    
        private function __construct()
        {
            $this->path = __DIR__."/config/";
        }
    
        public static function instance()
        {
            if (!(self::$instance instanceof Config)) {
                self::$instance = new Config();
            }
            return self::$instance;
        }
        
        public function offsetExists($offset)
        {
            return isset($this->config[$offset]);
        }
        
        public function offsetGet($offset)
        {
            if (empty($this->config[$offset])) {
                $this->config[$offset] = require $this->path.$offset.".php";
            }
            return $this->config[$offset];
        }
    
        public function offsetSet($offset, $value)
        {
            throw new \Exception('不提供设置配置');
        }
    
        public function offsetUnset($offset)
        {
            throw new \Exception('不提供删除配置');
        }
    }
    
    $config = Config::instance();
    
    //获取 app.php 文件的 name
    echo $config['app']['name'].PHP_EOL; //app name
    
    //获取 database.php 文件 mysql 的 user 配置
    echo $config['database']['mysql']['user'].PHP_EOL; // root
    
    

    如果你给我一样热爱 PHP,欢迎加入 QQ 群: 339803849 一起讨论

    声明

    文章转载说明出处,本文地址: http://moell.cn/article/29

    1 条回复    2016-10-30 23:37:27 +08:00
    param
        1
    param  
       2016-10-30 23:37:27 +08:00
    我仿佛又听到有人在背后偷偷 @我
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2590 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 15:28 · PVG 23:28 · LAX 08:28 · JFK 11:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.