web應用高複用,可擴充套件實現的一點設計思路
阿新 • • 發佈:2019-01-25
一:環境配置
開發環境:lnmp
開發框架:Yii2.0
二:目的
1.實現業務流程的清晰化
2.實現功能的高可複用性
3.實現業務的高可擴充套件性
4.可在web app,console app, api等形式中自由遷移
三:實現思路
1.針對不同的業務流程,定製不同的服務;
2.服務是由元件組合而成,單個元件有一個選擇器,用於選擇元件的不同功能,選擇器會內建幾個通用型,還可以自定義實現,從而保證功能變化的靈活性;
3.服務會註冊一個數據介面卡,用於適配不同的資料來源,保證功能元件獲取資料的統一,從而達到功能元件複用目的;
4.服務會註冊一個互動介面卡,用於適配不同的互動方式,保證互動方式的靈活性。
四:UML類圖
//下面是實現的部分程式碼例項
class TestOneController extends BaseController
{
public function actionCreate()
{
$dataAdapter = new DataAdapter();//未實現
$createOrderService = \Yii::$app->get('create-order');
$createOrderService->setDataAdapter($dataAdapter);//未實現
$createOrderService ->setOrderComponents(
[
'save-test-one' => [
'class' => 'app\services\order\components\SaveTestOne',
'selector' => 'app\services\order\selectors\GeoSelector',
]
]
);
$createOrderService ->setInteraction([
'save-test-one' => function () {
return 'error';
},
'success' => function () {
return 'success';
}
]);
return $createOrderService->run();
}
}
1.服務實現
abstract class AbstractOrderService extends ServiceLocator
{
protected $orderComponentList = [];
public function run()
{
try {
foreach ($this->orderComponentList as $each) {
$object = $this->get($each);
$object->execute();
}
} catch(Exception $e) {
throw new Exception($e->getMessage());
}
}
public function setOrderComponent($id, $definition)
{
array_push($this->orderComponentList, $id);
$this->set($id, $definition);
}
public function setOrderComponents($components)
{
foreach ($components as $id => $component) {
$this->setOrderComponent($id, $component);
}
}
}
class CreateOrderService extends AbstractOrderService
{
}
2.功能元件實現
abstract class AbstractComponent extends Component
{
public $selector = null;
final public function execute()
{
if (!is_null($this->selector) && is_callable($this->selector, true)) {
$selector = Yii::createObject([
'class' => $this->selector,
'component' => $this,
]);
$className = $selector->execute();
$object = Yii::createObject($className);
return $object->run();
} else {
return $this->run();
}
}
abstract public function run();
}
class SaveTestOne extends AbstractComponent
{
public function run()
{
var_dump('abcdefg!');
}
}
class BrSaveTestOne extends AbstractComponent
{
public function run()
{
var_dump('BrSaveTestOne');
}
}
3.選擇器實現
abstract class AbstractSelector extends Component
{
public $component;
abstract public function execute();
}
class GeoSelector extends AbstractSelector
{
public function execute()
{
return 'app\services\order\components\BrSaveTestOne';
}
}
4.資料介面卡實現
未完成
5.互動介面卡實現
未完成
以上是比較簡陋的思路體現,語言表達有不近如意之處,還請勿怪!