[英]Two models with shared methods and same table? [CakePHP]
我目前有兩個模型:產品和服務。 兩者共享相同的表結構和相同的方法。 但是,當我更新一種方法時,我必須對另一種 model 執行相同的操作。 它變得一團糟,更不用說我造成了冗余,這不是可用的最佳實踐。
我知道模型可以鏈接到同一個表,所以我只需要在 model 中添加一個$useTable = 'stuff'
並且我可以添加一個type
字段。 但是,我無法弄清楚如何創建“父”model,因為每個 model 都擴展了 AppModel。
公平地說,我對 OOP 幾乎一無所知,所以我可能會遺漏一些非常明顯和簡單的東西。
在不知道如何將兩個孩子(產品和服務)擴展到父母(東西)的情況下,我會做的事情是:
$this->Stuff->type = 'product';
$products = $this->Stuff->findAvailable();
但我敢打賭,有一種更簡單、更清潔的方法。
謝謝。
使用行為。 如食譜中所述:
Model 行為是一種組織 CakePHP 模型中定義的一些功能的方法。 它們允許我們分離可能與 model 沒有直接關系但需要存在的邏輯。 通過提供一種簡單而強大的方式來擴展模型,行為允許我們通過定義一個簡單的 class 變量來將功能附加到模型。 這就是行為允許模型擺脫所有額外權重的方式,這些權重可能不屬於他們正在建模的業務合同的一部分,或者不同模型也需要這些額外的權重,然后可以進行推斷。
http://book.cakephp.org/view/1071/Behaviors
該鏈接應該讓您很好地了解從哪里開始。
您基本上使用的是可繼承性和可擴展性:
可擴展:[刪除鏈接以符合我的新手狀態。 它在下面來自 gitub 的文件中]
其中被納入: https://github.com/CakeDC/utils/blob/master/models/behaviors/inheritable.php
我只是使用了同樣的方法(也適用於產品和服務)。 實際上,我對每個公共字段和子類型(2 類產品和 3 類服務)都有不同的字段,因此我創建了 Offer model 並帶有一個如下所示的優惠表:
CREATE TABLE `offers` (
`id` int(11) NOT NULL AUTO_INCREMENT, //common
`carrier_id` int(11) DEFAULT NULL, //common
`category_id` int(11) DEFAULT NULL, //common
`name` varchar(255) DEFAULT NULL, //common
`description` longtext, //common
`type` ENUM('Product', 'Service') not null default 'Product',
`sku` varchar(255) DEFAULT NULL, //product
`make` varchar(255) DEFAULT NULL, //product
`model` varchar(255) DEFAULT NULL, //product
`listprice` decimal(9,2) DEFAULT NULL, //product
`soc_code` varchar(255) DEFAULT NULL, //service
`unit` varchar(255) DEFAULT NULL, //service
`units` int(11) DEFAULT NULL, //service
`mrc` decimal(9,2) DEFAULT NULL, //service
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `carrier_id` (`carrier_id`),
KEY `category_id` (`category_id`),
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
然后我的報價 model 看起來像這樣:
<?php
class Offer extends AppModel {
public $name = 'Offer';
public $useTable = 'offers';
public $displayField = 'name';
public $belongsTo = array(
'Carrier' => array(
'className' => 'Carrier',
'foreignKey' => 'carrier_id',
),
'Category' => array(
'className' => 'Category',
'foreignKey' => 'category_id',
)
);
使用產品 model:
<?php
App::import('Model', 'Offer');
class Product extends Offer {
public $name = 'Product';
public $useTable = 'offers';
public $displayField = 'name';
public $actsAs = array('utils.inheritable');
(服務實際上是相同的)。
然后,您在 Offer model 中創建所有方法,並且在這些模型中只存在任何適合子類產品或服務的東西。
如果您還沒有找到解決方案,我希望這會有所幫助。
將兩個模型共享的方法放入您的AppModel :
這個中間 class AppModel 是空的,如果您還沒有創建自己的,則從 /cake/ 文件夾中獲取。 覆蓋 AppModel 允許您定義應該對應用程序中的所有模型可用的功能。 為此,您需要創建自己的 app_model.php 文件,該文件位於 /app/ 文件夾的根目錄中。
您的產品和服務模型擴展了 AppModel。 這意味着 AppModel 中的所有方法都可供他們使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.