2012-03-08 5 views
3

현재 저는 save()를 호출하기 전에 객체에 다양한 요소를 추가해야하는 Lithium 응용 프로그램을 개발 중입니다. 이상적으로리튬 일반 모델 필터

나는 다음과 같은 모델 클래스 (다른 모델은 확장 기본 모델)에 적용 할 필터를 작성할 수있을 것입니다 :

Model::applyFilter('save', function($self, $params, $chain) { 
    // Logic here 
}); 

이 가능합니까? 그렇다면 부트 스트랩 된 파일이어야합니까?

답변

5

난 당신이 무슨 말을하는지 오해 아니에요 경우, 당신이 원하는 필터, 예를 들면, 저장하기 전에 객체에 'created'또는 'modified'값을 자동으로 추가하십시오.

내가 어떻게하는지. 내 extensions/data/Model.php

<?php 
namespace app\extensions\data; 
use lithium\security\Password; 

class Model extends \lithium\data\Model { 

    public static function __init() { 
     parent::__init(); 

     // {{{ Filters 
     static::applyFilter('save', function($self, $params, $chain) { 
      $date = date('Y-m-d H:i:s', time()); 
      $schema = $self::schema(); 

      //do these things only if they don't exist (i.e. on creation of object) 
      if (!$params['entity']->exists()) { 

       //hash password 
       if (isset($params['data']['password'])) { 
        $params['data']['password'] = Password::hash($params['data']['password']); 
       } 

       //if 'created' doesn't already exist and is defined in the schema... 
       if (empty($params['date']['created']) && array_key_exists('created', $schema)) { 
        $params['data']['created'] = $date; 
       } 
      } 

      if (array_key_exists('modified', $schema)) { 
       $params['data']['modified'] = $date; 
      } 
      return $chain->next($self, $params, $chain); 
     }); 
     // }}} 
    } 
} 

?> 

에서

는 좀 비밀번호뿐만 아니라이 해시 있습니다. 기능에 영향을 미치지 않고 제거 할 수 있습니다.

4

필터는 상속 *을 지원하지 않습니다.

OOP를 사용하고 오버플로 된 save() 메소드가있는 BaseModel 클래스가 있고 모든 앱 모델이 상속하는 것이 좋습니다.

다른 방법으로는 부트 스트랩 된 파일에서 각 모델에 필터를 지연 적용하는 것이 좋습니다. 예를 들어 : $timestamp 폐쇄

Filters::apply('app\models\Documents', 'save', $timestamp); 
Filters::apply('app\models\Queries', 'save', $timestamp); 
Filters::apply('app\models\Projects', 'save', $timestamp); 

* 상속 planned하지만 아직 implemented