Skip to content

Instantly share code, notes, and snippets.

@sanhuang
Last active September 30, 2016 14:48
Show Gist options
  • Save sanhuang/05c3df4b11d041c0e186d540ad83a823 to your computer and use it in GitHub Desktop.
Save sanhuang/05c3df4b11d041c0e186d540ad83a823 to your computer and use it in GitHub Desktop.
透過Phalcon修改Dev-Tools,讓產生model檔案時可以讀入欄位註解,並且於Controllers內取出使用方法

Generate model file with comment of field

最近發現了Phalcon/Annotations強大之處,不斷嘗試透過他可以直接根據註解來作為設定值機制,用來處理ACL配置與Model轉換匯入功能都有很不錯的幫助。 首先,在設計資料庫階段,多半會直接將資料欄位註解寫入,但透過Phalcon開發工具產生model檔案,預設是無法取得欄位註解的。 假設你要加上得逐筆一一對上才可,針對中大型專案而言相當費時,至於加上註解的好處主要兩點

  • 開發期間不用切換到DB GUI上去查欄位用途
  • 假設今天要做匯入資料功能,多半取得資料可能是中文標頭才方便人工作業,匯入時可以直接根據註解來做對應不需額外定義!
    • 反之也可簡單寫一隻建立格式檔的程式產出以註解作為標頭的csv檔案!

change template file of model generate

get comment of field in the table and write into tempalte

read comment from model used by $this->annotations

In the Action()
```php
$reflection=$this->annotations->get("[modelclass]");
foreach($reflection->getPropertiesAnnotations() as $key => $collection) {
if( $collection->has('comment') ){
$anno=$collection->get('comment');
var_dump($anno->getArgument(0));
}
}
```
*filepath* scripts/Phalcon/Builder/Generator/Snippet.php
At line158
```php
public function getAttributes($type, $visibility, $fieldName, $comment)
{
$templateAttributes = <<<EOD
/**
* @comment('%s')
* @var %s
*/
%s \$%s;
EOD;
return PHP_EOL.sprintf($templateAttributes, $comment, $type, $visibility, $fieldName).PHP_EOL;
```
*filepath* scripts/Phalcon/Builder/Project/Model.php
At line441
```php
$cols = $db->fetchAll("SHOW FULL COLUMNS FROM `{$table}`");
foreach ($fields as $field) {
if (array_key_exists(strtolower($field->getName()), $exclude)) {
continue;
}
$type = $this->getPHPType($field->getType());
$key=array_search($field->getName(), array_column($cols, 'Field'));
if ($useSettersGetters) {
$attributes[] = $this->snippet->getAttributes($type, 'protected', $field->getName(), $cols[$key]['Comment']);
$methodName = Utils::camelize($field->getName());
$setters[] = $this->snippet->getSetter($field->getName(), $type, $methodName);
if (isset($this->_typeMap[$type])) {
$getters[] = $this->snippet->getGetterMap($field->getName(), $type, $methodName, $this->_typeMap[$type]);
} else {
$getters[] = $this->snippet->getGetter($field->getName(), $type, $methodName);
}
} else {
$attributes[] = $this->snippet->getAttributes($type, 'public', $field->getName(), $cols[$key]['Comment']);
}
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment