본문 바로가기

개발/프로그래밍

PHP Interceptor

* PHP Built-In Interceptor메소드들

MethodDescription
__get($property)Invoked when an undefined property is accessed
__set($property)Invoked when a value is assigned to an undefined property
__isset($property)Invoked when isset() is called on an undefined property
__unset($property)Invoked when unset() is called on an undefined property
__call($method, $arg_array)Invoked when an undefined method is called

http://develturk.com/2009/04/18/interceptor-methods-__call-php-overloading/


* __call() override

/*
02.*  An Interceptor Example for __call() method
03.*  Ersin Güvenç.
04.*/
05. 
06.Class NameWriter
07.{
08./*
09.*  @param - 1: name  - instance of Name Class
10.*/
11.function writeName(Name $name)
12.{
13.print $name->getName();
14.}
15. 
16.function writeAge(Name $name)
17.{
18.print $name->getAge();
19.}
20. 
21.}  //end of the class.
22. 
23.Class Name
24.{
25.private $writer//NameWriter instance
26. 
27.function __construct(NameWriter $writer)
28.{
29.$this->writer = $writer;
30.}
31. 
32./* our __call method */
33.function __call($methodname$args)
34.{
35.if(method_exists($this->writer, $methodname))
36.{
37.return $this->writer->$methodname($this);
38.}
39.}
40. 
41.function getName() { return "John"; }
42.function getAge() { return "27";}
43. 
44.//end of the class.
45. 
46.//Our Super Object.
47.$name new Name( new NameWriter() );
48. 
49.$name->writeName();
50.$name->writeAge();
51. 
52.//OUTPUT
53.//Jonn
54.//27


* __autoload() override

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 절대 경로
define('_ROOT_PATH_', '/www/설치경로');
 
# 클래스 자동 인클루드
function __autoload($class_name)
{
        # 클래스명중 경로 추출
    $tmp_args = explode(' ', preg_replace( '/([a-z0-9])([A-Z])/', "$1 $2",$class_name));
    $class_path_name = sprintf("%s/{$class_name}",strtolower($tmp_args[0]));
     
    # 체크
         if(!class_exists($class_path_name,false))
    {
        # classes 폴더
        if(file_exists(_ROOT_PATH_.'/classes/'.$class_path_name.'.class.php') !==false){
            include_once _ROOT_PATH_.'/classes/'.$class_path_name.'.class.php';
        }
 
        # modules 폴더
        else if(file_exists(_ROOT_PATH_.'/modules/'.$class_path_name.'.class.php') !==false){
            include_once _ROOT_PATH_.'/modules/'.$class_path_name.'.class.php';
        }
 
        # 기타 만든 클래스 폴더 [첫대문자만 폴더로 지원]
        # ( /my/MyTest.class.php -> MyTest.class.php)
        else if(file_exists(_ROOT_PATH_.'/'.$class_path_name.'.class.php') !==false){
            include_once _ROOT_PATH_.'/'.$class_path_name.'.class.php';
        }
    }
}

PHP5에서 기본제공하는 spl_autoload_register 함수를 이용할수도 있다.

(실사용예는 오픈소스인 Log4php소스코드 참고할것)

'개발 > 프로그래밍' 카테고리의 다른 글

Http Header Info  (0) 2012.10.24
OS Scheduling Algorithm  (0) 2012.10.09
JVM에서 PHP 구동  (0) 2012.06.23
Groovy  (0) 2012.04.10
jstat 사용법  (0) 2012.03.15