我以最不优雅的方式实现了一个控制器动作。怎么会变得更好?表类就像在bin/cake bake
之后。我认为创建实体的部分可以非常简单。
我在做什么: 图书 - belongsTo - > 发布商< - habtm - > Publishernumbers 将Book添加到数据库时,将从ISBN编号中提取publishernumber。然后,该数字以habtm关系链接到发布者。我需要这个用户在表单中键入isbn时向用户建议一些发布者。
该代码目前有效,但在一年内,只有上帝知道我在这里做了什么。第一部分很简单。
public function add()
{
$book = $this->Books->newEntity();
$associations = ['associated' =>
[
'Tags',
'Publishers',
'Publishers.Publishernumbers'
]
];
if ($this->request->is('post')) {
$data= $this->request->data;
$publisher = $this->Books->Publishers->get(
$this->request->data['publisher_id'],
['contain' => ['Publishernumbers']]
);
unset($data['publisher_id']);
$book->publisher = $publisher;
//extract group- and publishernumber from the ISBN
$this->loadComponent('Isbn.Isbn');
$split = $this->Isbn->splitIsbn($this->request->data['isbn']);
$publishernumber = $split[1].$split[2];
这是混乱开始的部分。我认为这可以做得更优雅。
//check if the publisher contains already the $publishernumber
//and if not, add it to the entity
$new = true;
foreach ($book->publisher->publishernumbers as $n){
if ($n->number == $publishernumber){
$new = false;
}
}
if ($new){
$existingNumber = $this->Books->Publishers->Publishernumbers
->findByNumber($publishernumber)
->first();
if (!$existingNumber){
//publishernumber does not exist in the database
$pubnumber = $this->Books->Publishers->Publishernumbers
->newEntity();
$pubnumber = $this->Books->Publishers->Publishernumbers
->patchEntity($pubnumber, ['number' => $publishernumber]);
$book->publisher->publishernumbers[] = $pubnumber;
} else {
//publishernumber exists in the database
//but is not associated with the publisher
$book->publisher->publishernumbers[] = $existingNumber;
}
$book->publisher->dirty('publishernumbers', true);
}
$book = $this->Books->patchEntity($book, $data, $associations);
保存
if ($this->Books->save($book, $associations)){
Cache::delete('exlibrisBooksIndex');
$this->Flash->success(__('The book has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Error.'));
}
}
$publishers = $this->Books->Publishers->find('list')
->order('name')
->toArray();
$this->set(compact('book', 'publishers'));
$this->set('_serialize', ['book']);
}