1

我以最不优雅的方式实现了一个控制器动作。这怎么能变得更好?表类就像 after bin/cake bake。我认为创建实体的部分可以非常简单。

我在做什么: Books --belongsTo--> Publishers <--habtm--> Publishernumbers 将 Book 添加到数据库时,publishernumber 是从 ISBN 号中提取的。然后,此编号以 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']);
}
4

0 回答 0