搜尋
首頁後端開發php教程關注點分離 (SoC)

Separation of Concerns (SoC)

關鍵實施範例

1. 資料庫層分離

// Bad - Mixed concerns
class User {
    public function save() {
        $db = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');
        $stmt = $db->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
        $stmt->execute([$this->name, $this->email]);
    }
}

// Good - Separated database logic
class User {
    private string $name;
    private string $email;
}

class UserRepository {
    private PDO $db;

    public function save(User $user) {
        $stmt = $this->db->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
        $stmt->execute([$user->getName(), $user->getEmail()]);
    }
}

這個很好的範例將資料結構(User)與儲存邏輯(UserRepository)分開。這使得程式碼更易於維護,並且允許在不修改 User 類別的情況下更改儲存方法。

2. 驗證分離

// Bad - Mixed validation and business logic
class Order {
    public function process() {
        if (empty($this->items)) {
            throw new Exception('Order cannot be empty');
        }
        if ($this->total getItems())) {
            $errors[] = 'Order cannot be empty';
        }
        if ($order->getTotal() 



<p>驗證邏輯移至專用驗證器類,使 Order 類別專注於業務邏輯。 </p>

<h3>
  
  
  3.視圖/模板分離
</h3>



<pre class="brush:php;toolbar:false">// Bad - Mixed HTML and logic
class ProductPage {
    public function show($id) {
        $product = $this->getProduct($id);
        echo "<h1 id="product-gt-name">{$product->name}</h1>";
        echo "<p>Price: ${$product->price}</p>";
    }
}

// Good - Separated presentation
class ProductController {
    public function show($id) {
        $product = $this->productRepository->find($id);
        return $this->view->render('product/show', ['product' => $product]);
    }
}

// product/show.php template
<h1 id="htmlspecialchars-product-gt-name-gt">= htmlspecialchars($product->name) ?></h1>
<p>Price: $= htmlspecialchars($product->price) ?></p>

這個很好的例子將顯示邏輯分離到模板中,使程式碼更易於維護,並允許設計人員獨立工作。

4. 服務層分離

// Bad - Mixed business logic
class OrderController {
    public function checkout() {
        $order = new Order($_POST['items']);
        $payment = new Payment($_POST['card']);
        $payment->process();
        $order->updateStatus('paid');
        $email = new EmailService();
        $email->sendConfirmation($order);
    }
}

// Good - Separated services
class OrderService {
    private PaymentService $paymentService;
    private EmailService $emailService;

    public function processOrder(Order $order, PaymentData $paymentData): void {
        $this->paymentService->process($paymentData);
        $order->updateStatus('paid');
        $this->emailService->sendConfirmation($order);
    }
}

class OrderController {
    public function checkout() {
        $this->orderService->processOrder($order, $paymentData);
    }
}

服務層處理複雜的業務邏輯,使控制器專注於請求處理。

5.配置分離

// Bad - Hardcoded configuration
class EmailSender {
    private $host = 'smtp.example.com';
    private $port = 587;

    public function send($message) {
        // Sending logic using hardcoded values
    }
}

// Good - Separated configuration
// config/mail.php
return [
    'host' => 'smtp.example.com',
    'port' => 587
];

class EmailSender {
    private array $config;

    public function __construct(array $config) {
        $this->config = $config;
    }

    public function send($message) {
        // Sending logic using config values
    }
}

配置與實作分離,使程式碼更加靈活可維護。無需修改程式碼即可更改設定。

以上是關注點分離 (SoC)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使PHP應用程序更快如何使PHP應用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能優化清單:立即提高速度PHP性能優化清單:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

PHP依賴注入:提高代碼可檢驗性PHP依賴注入:提高代碼可檢驗性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能優化:數據庫查詢優化PHP性能優化:數據庫查詢優化May 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

簡單指南:帶有PHP腳本的電子郵件發送簡單指南:帶有PHP腳本的電子郵件發送May 12, 2025 am 12:02 AM

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

PHP性能:識別和修復瓶頸PHP性能:識別和修復瓶頸May 11, 2025 am 12:13 AM

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显著提升PHP应用的性能。

PHP的依賴注入:快速摘要PHP的依賴注入:快速摘要May 11, 2025 am 12:09 AM

依賴性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增強量強制性,可驗證性和MATIALWINABIOS.ItallowSpasspassingDepentenciesLikEdenciesLikedAbaseConnectionStoclasseconnectionStoclasseSasasasasareTers,interitationAseTestingEaseTestingEaseTestingEaseTestingEasingAndScalability。

提高PHP性能:緩存策略和技術提高PHP性能:緩存策略和技術May 11, 2025 am 12:08 AM

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中