Table of Contents
回复内容:
Home Backend Development PHP Tutorial 如何设计合理的service?

如何设计合理的service?

Jun 06, 2016 pm 08:34 PM
java php development specifications programming

今天碰到一个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>
Copy after login

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

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

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

Statement of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

H5: Key Improvements in HTML5 H5: Key Improvements in HTML5 Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

Discuss situations where writing platform-specific code in Java might be necessary. Discuss situations where writing platform-specific code in Java might be necessary. Apr 25, 2025 am 12:22 AM

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

Explain how to use sessions for user authentication. Explain how to use sessions for user authentication. Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles