2016-06-11 1 views
0

과거에는 많은 것들을 위해 자체 클래스를 사용했습니다. 나는 PHP 자체가 stdClasses를 제공한다는 것을 알고있다. 그래서 저는 수백 개의 새로운 클래스 ("도우미 클래스")를 만들 필요가 없기 때문에 작은 오브젝트에이 클래스를 사용하는 것이 더 효율적이라고 생각합니다.PHP stdClass 대 "normal named"클래스

예 :

클래스
public function getStatus() { 
    $status = new Status("1", "success"); 
    return $status 
} 

:

class Status 
{ 
    private $id; 
    private $name; 

    public function __construct($id, $name) 
    { 
     $this->id = $id; 
     $this->name = $name; 
    } 

    public function getId() 
    { 
     return $this->id; 
    } 

    public function getName() 
    { 
     return $this->name; 
    } 

} 

가 (당신이 볼 수있는 유일한 이유는 내가 같은 클래스가 필요하다 "반환"데이터)

그래서 내가 말했듯이, 매번 이런 식으로 코드를 작성하면 약간의 사용을 위해 많은 클래스를 만들어야합니다.

내 경우와 같이 stdClass 개체를 사용하는 것이 더 좋지 않습니까? 이 아이디어의 단점은 무엇입니까?

+0

좋은 생각이 아니다 : 가난한 영어 : 예를 들어

죄송합니다. 별도의 목적으로 별도의 클래스와 명시적인 클래스가 있어야합니다. 경험 법칙 : 암시 적으로 명시 적으로 _ 선택하십시오. 그렇지 않으면 코드를 읽기가 어렵고 디버그하기가 더 어려워지고 IDE는 자동 완성 등을 도울 수 없습니다. – arkascha

+0

부모 클래스를 사용하지 않고'__get'과'__set' 메소드를 사용하는 이유는 무엇입니까? – smoqadam

+0

@arkascha 나는 그것을 이해하지만, 더 큰 것들을 위해, 나는 보통의 객체 (사용자 객체, ...)를 사용한다. 그것은 2-3 변수를 가진 아주 작은 객체에 관한 것이고 어떤 것은 메소드를 얻습니다. – user6391870

답변

0

필자와 마찬가지로 ArrayObject, Data, DataAccess 등과 같은 헬퍼/클래스를 더 잘 사용하십시오. 이 헬퍼/클래스는 빠른 저장 공간 및 데이터 액세스를 제공합니다.

stdClass 객체를 사용하지 않습니다. json_decode와 같은 함수를 사용하더라도 두 번째 인수를 true로 설정하면 stdClasses의 배열 대신 배열의 배열을 얻을 수 있습니다.

나를 이해하시기 바랍니다.

/** 
* @package com_zoo 
* @author YOOtheme http://www.yootheme.com 
* @copyright Copyright (C) YOOtheme GmbH 
* @license http://www.gnu.org/licenses/gpl.html GNU/GPL 
*/ 

/** 
* Class for reading and writing in various formats 
* 
* @package Framework.Classes 
*/ 
class AppData extends ArrayObject 
{ 

    /** 
    * Class constructor 
    * 
    * @param array $data The data array 
    */ 
    public function __construct($data = array()) 
    { 
     parent::__construct($data ? $data : array()); 
    } 

    /** 
    * Checks if the given key is present 
    * 
    * @param string $name The key to check 
    * 
    * @return boolean If the key was found 
    * 
    * @since 1.0.0 
    */ 
    public function has($name) 
    { 
     return $this->offsetExists($name); 
    } 

    /** 
    * Get a value from the data given its key 
    * 
    * @param string $key  The key used to fetch the data 
    * @param mixed $default The default value 
    * 
    * @return mixed The fetched value 
    * 
    * @since 1.0.0 
    */ 
    public function get($key, $default = null) 
    { 

     if ($this->offsetExists($key)) { 
      return $this->offsetGet($key); 
     } 

     return $default; 
    } 

    /** 
    * Set a value in the data 
    * 
    * @param string $name The key used to set the value 
    * @param mixed $value The value to set 
    * 
    * @return AppData The AppData object itself to allow chaining 
    * 
    * @since 1.0.0 
    */ 
    public function set($name, $value) 
    { 
     $this->offsetSet($name, $value); 

     return $this; 
    } 

    /** 
    * Remove a value from the data 
    * 
    * @param string $name The key of the data to remove 
    * 
    * @return AppData The AppData object itself to allow chaining 
    * 
    * @since 1.0.0 
    */ 
    public function remove($name) 
    { 
     $this->offsetUnset($name); 

     return $this; 
    } 

    /** 
    * Magic method to allow for correct isset() calls 
    * 
    * @param string $name The key to search for 
    * 
    * @return boolean If the value was found 
    * 
    * @since 1.0.0 
    */ 
    public function __isset($name) 
    { 
     return $this->offsetExists($name); 
    } 

    /** 
    * Magic method to get values as object properties 
    * 
    * @param string $name The key of the data to fetch 
    * 
    * @return mixed The value for the given key 
    * 
    * @since 1.0.0 
    */ 
    public function __get($name) 
    { 
     return $this->offsetGet($name); 
    } 

    /** 
    * Magic method to set values through object properties 
    * 
    * @param string $name The key of the data to set 
    * @param mixed $value The value to set 
    * 
    * @since 1.0.0 
    */ 
    public function __set($name, $value) 
    { 
     $this->offsetSet($name, $value); 
    } 

    /** 
    * Magic method to unset values using unset() 
    * 
    * @param string $name The key of the data to set 
    * 
    * @since 1.0.0 
    */ 
    public function __unset($name) 
    { 
     $this->offsetUnset($name); 
    } 

    /** 
    * Magic method to convert the data to a string 
    * 
    * Returns a serialized version of the data contained in 
    * the data object using serialize() 
    * 
    * @return string A serialized version of the data 
    * 
    * @since 1.0.0 
    */ 
    public function __toString() 
    { 
     return empty($this) ? '' : $this->_write($this->getArrayCopy()); 
    } 

    /** 
    * Utility Method to serialize the given data 
    * 
    * @param mixed $data The data to serialize 
    * 
    * @return string The serialized data 
    * 
    * @since 1.0.0 
    */ 
    protected function _write($data) 
    { 
     return serialize($data); 
    } 

    /** 
    * Find a key in the data recursively 
    * 
    * This method finds the given key, searching also in any array or 
    * object that's nested under the current data object. 
    * 
    * Example: 
    * <code> 
    * $data->find('parentkey.subkey'); 
    * </code> 
    * 
    * @param string $key  The key to search for. Can be composed using $separator as the key/subkey separator 
    * @param mixed $default The default value 
    * @param string $separator The separator to use when searching for subkeys. Default is '.' 
    * 
    * @return mixed The searched value 
    * 
    * @since 1.0.0 
    */ 
    public function find($key, $default = null, $separator = '.') 
    { 

     $key = (string)$key; 
     $value = $this->get($key); 

     // check if key exists in array 
     if ($value !== null) { 
      return $value; 
     } 

     // explode search key and init search data 
     $parts = explode($separator, $key); 
     $data = $this; 

     foreach ($parts as $part) { 

      // handle ArrayObject and Array 
      if (($data instanceof ArrayObject || is_array($data)) && isset($data[$part])) { 

       if ($data[$part] === null) { 
        return $default; 
       } 

       $data =& $data[$part]; 
       continue; 
      } 

      // handle object 
      if (is_object($data) && isset($data->$part)) { 

       if ($data->$part === null) { 
        return $default; 
       } 

       $data =& $data->$part; 
       continue; 
      } 

      return $default; 
     } 

     // return existing value 
     return $data; 
    } 

    /** 
    * Find a value also in nested arrays/objects 
    * 
    * @param mixed $needle The value to search for 
    * 
    * @return string The key of that value 
    * 
    * @since 1.0.0 
    */ 
    public function searchRecursive($needle) 
    { 
     $aIt = new RecursiveArrayIterator($this); 
     $it = new RecursiveIteratorIterator($aIt); 

     while ($it->valid()) { 
      if ($it->current() == $needle) { 
       return $aIt->key(); 
      } 

      $it->next(); 
     } 

     return false; 
    } 

    /** 
    * Return flattened array copy. Keys are <b>NOT</b> preserved. 
    * 
    * @return array The flattened array copy 
    * 
    * @since 1.0.0 
    */ 
    public function flattenRecursive() 
    { 
     $flat = array(); 
     foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($this)) as $value) { 
      $flat[] = $value; 
     } 

     return $flat; 
    } 
} 



$array = array(
    'simple' => 'very simple array', 
    'big' => array(
     'bigbig' => array(
      'bigbigbig' => 'third level' 
     ) 
    ) 
); 
$data = new AppData($array); 

echo $data->get('simple');    // very simple array 
echo $data->find('big.bigbig.bigbigbig'); // third level 
echo $data->get('not_found', 'novalue'); // novalue 
+0

이와 비슷한 것 - https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/ParameterBag.php 그러나 재귀 적 검색은 없습니다. D 큰 json 데이터로 작업 할 때 실제 경제가 그 자리를 차지합니다. – Tapakan

+0

예를 들어 주시겠습니까? – user6391870