search
HomeBackend DevelopmentPHP Tutorial如何设计合理的service?

如何设计合理的service?

Jun 06, 2016 pm 08:34 PM
javaphpdevelopment specificationsprogramming

今天碰到一个bug,最后发现原因应该就是service的设计不当(另一个提问)
那么我们应该如何设计合理的service?有哪些要注意的?什么才是好的service?有哪些的例子可以参考?

回复内容:

今天碰到一个bug,最后发现原因应该就是service的设计不当(另一个提问)
那么我们应该如何设计合理的service?有哪些要注意的?什么才是好的service?有哪些的例子可以参考?

我的解决办法如下,有什么缺点请指教:

Service应该分为2种:1,名词Service; 2, 行为Service
如:UserService 与 RegisterService

对于【名词Service】其里面每个method都必须返回相应的对象,如UserService下的upgrade(uid)就必须返回被升级后的user对象。

对于【行为Service】只对外暴露出一个execute(data),excute(data)必须返回行为成功与否的状态以及被施加这个行为的对象,如RegisterService下的excute(data)就必须返回注册成功与否,以及如果成功了它影响的对象。

通常我们约定对外只调用【行为Service】,再在【行为Service】里调用多个【名词Service】和其他【行为Service】,如在RegisterService::execute(data)里调用UserService::create(), UserService::markNewbee(uid),SendEmailService::execut()等;

【名词Service】中允许调用别的【名词Service】,但不允许调用【行为Service】,如UserService::upgrade不单单可以修改user也可以调用LogService::create来创建log,但不能调用LogoutService::execute()来登出用户。

可以简单的理解为一个Model处理它那张数据库表,一个【名词Service】处理多个Model,一个【行为Service】处理多个【名词Service】,这里【行为Service】也就是设计模式里的facade,可以配合command模式使用。

所有Service的每个method的入参都可以是id或者对象实例,如upgrade()可以接受uid也可以接受user作为入参。

回到我的另一个提问,可以这么写

<code>class AService
{
    function get(aid_or_object)
    {
        if (aid_or_object instanceOf A) {
            return aid_or_object;
        }
        return A.getById(aid);
    }
}

class PService
{
    function get(pid_or_object)
    {
        if (pid_or_object instanceOf P) {
            return pid_or_object;
        }
        return P.getById(pid);
    }
}


class Do2Service
{
    function execute(aid_or_object, pid_or_object = null)
    {
        a = AService.get(aid_or_object);
        if (pid_or_object instanceOf P) {
            p = pid_or_object
        } else {
            p = PService.get(a.pid);
        }
        p.s = 'zz';
        p.save();
        a.save();
        return [:success, a, p];
    }
}

class Do3Service
{
    function execute(pid_or_object)
    {
        p = PService.get(pid_or_object);
        p.s = 'cc';
        p.save();
        return [:success, p];
    }
}

class Do1Service
{
    function execute(pid_or_object)
    {
        p = PService.get(pid_or_object);
        p.s = 'yy' if condition1        
        result, a, p = Do2Servce.execute(p.aid, p) if condition2
        result, p = Do3Servce.execute(p) if condition3

        p.a = 'a';
        p.b = 'b';

        p.save()

        return [:success, p, a];
    }
}
</code>

你的问题的本质,是两个“主语”(只是在你的案例中恰好都是service而已)的各自一个“行为”(do1 和 do2)含有了完全相同的一个“行动效果”(修改p.s的值)。
冲突不在于service,而在于行动效果冗余。
试想一下,换一个案例,其中只有一个主语,两个行为(do1 和 do2)都是它的,那么问题也是等价的。
两个行为有重叠的行动效果,实在太常见的了。
关键在于,你怎样界定,哪种重叠是满足需求的?哪种是错误、不合理的?

举一个满足需求的例子:
需求是:p是一个鼠标悬停的tips(界面组件)。先根据鼠标坐标,赋值p.top为一个值。随后,计算tips是否超出了窗口边缘。如果是,则计算tips的top的最大值(因为窗口大小可能会被改变,所以需要计算),然后赋值p.top为该最大值。p.left同理。
这是我做网页前端开发时遇到过的需求。

你的解决办法,大概可以解决你的那一个具体案例,但换成别的情况可能就又不对症了。
在我看来,关键在于,一个行为的源头(往往是事件)所导致一连串行动效果,其中要避免出现重叠;除非需求要求必要的重叠。
这“一连串”的“串法”,是设计上要想清楚的。你已经在朝这个方向努力了,只是关注点稍有偏离。
至于串的过程中的对象(主语/宾语)是不是service、是何种service,倒是没有关系。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),