search
HomeBackend DevelopmentPHP Tutorialmvc - PHP 中什么时候用 component 什么时候用 Model,特别迷惑

开始使用yii2,但是被里面的弄得很迷惑,component 和 model的区别是什么样的。

以下是一些自己的心得,可能有错误,请指正:

1)发现yii2一些规律,在 @app/models/*文件 有2种类型。比如InfoForm这样以Form结尾的文件都是继承自Model,而Info.php这样的表名的文件都是继承自 ActiveRecord 。但疑问的是在github上看到的一些yii2的程序,里面的全部都写在一个Info.php这样的里面。(不过网络上使用yii2开发的开源程序真的是少得可怜,没有研究)

2)component 与 model的区别到底是在哪里?什么情况下该用component 什么情况下该用model?貌似继承自 ActiveRecord 的 Info.php 这样的就只是一个单独的这样文件:

<code>php</code><code><br><?php namespace app\models;
use yii\base\ActiveRecord;
class Info extends ActiveRecord {
    public function static tableName(){
        return '{{%my_post}}';
    }
}

</code></code>

然后就没有写其他的功能代码了,其他的写在这个地方似乎不合适了。

3)接到上面第2点,比如当我要实现用户的积分扣除功能。流程逻辑应该如下吧:

<code>1.先检测用户当前的积分是否充足?如果不充足失败且提示。
2.执行积分扣除
3.成功写入积分变更日志
</code>

像第3点这样的,该写在那个文件,特别让人疑惑 /models/Member.php 还是 /models/MemberQuery.php 还是 /components/Member/ScoresUse.php

4)如果真的像 【积分扣除】【用户封禁】这样的功能都制作成单独的组件components,那么ActiveRecord models那么岂不就真的就只剩下第2点里面说的这一段内容的?另外如果真的是这样,那岂不component 变得异常的庞大,但问题是执行【积分扣除】【用户封禁】这样的操作,不是单独某个表的,如果放到 /models/Member.php 里面去执行,需要调用额外的其他表,显然又不符合规范,显得很混乱。

5)比如 【积分扣除】【用户封禁】这样的操作必须可以让正在登陆用户自行调用,又可以让登陆的管理员自行登陆,所以,似乎归类到 model来说完全不适合? 归类到 component 却又还不如直接用 function 单独函数更方便?比如执行 【积分扣除变更】功能:

<code>php</code><code>/**
 * @description 操作用户积分!
 * @param $mid
 * @param $jftype
 * @param string $tips
 * @param null $jfValue2
 * @return bool
 */
function log_jifen_change($mid, $jftype, $tips = '', $jfValue2 = null)
{
    global $dsql;

    $jfvalue = $jfValue2 && is_numeric($jfValue2) ? $jfValue2 : jifen_value($jftype);

    if ($dsql->ExecuteNoneQuery2("UPDATE #@__member SET scores=scores+'$jfvalue' WHERE mid='" . $mid . "' ")) {

        $rs = $dsql->GetOne("SELECT `scores` FROM `#@__member` WHERE `mid`='{$mid}' ");
        $scoresLeft = $rs['scores'];

        $setarr = array(
            'mid'     => $mid, //会员ID
            'jftype'  => $jftype, //积分代码
            'jftime'  => time(), //操作时间
            'jfvalue' => $jfvalue, //本次变更积分
            'tips'    => $tips, //提示内容
            'jfleft'  => $scoresLeft, //剩余的积分
        );

        $dsql->ExecuteNoneQuery("INSERT INTO gk_member_jflog SET " . MkSetSql($setarr));

        return $scoresLeft;
    }

    return false;
}

</code>

PHP中什么时候该用 component 什么时候该用 model?特别让人迷惑。。。

回复内容:

开始使用yii2,但是被里面的弄得很迷惑,component 和 model的区别是什么样的。

以下是一些自己的心得,可能有错误,请指正:

1)发现yii2一些规律,在 @app/models/*文件 有2种类型。比如InfoForm这样以Form结尾的文件都是继承自Model,而Info.php这样的表名的文件都是继承自 ActiveRecord 。但疑问的是在github上看到的一些yii2的程序,里面的全部都写在一个Info.php这样的里面。(不过网络上使用yii2开发的开源程序真的是少得可怜,没有研究)

2)component 与 model的区别到底是在哪里?什么情况下该用component 什么情况下该用model?貌似继承自 ActiveRecord 的 Info.php 这样的就只是一个单独的这样文件:

<code>php</code><code><br><?php namespace app\models;
use yii\base\ActiveRecord;
class Info extends ActiveRecord {
    public function static tableName(){
        return '{{%my_post}}';
    }
}

</code></code>

然后就没有写其他的功能代码了,其他的写在这个地方似乎不合适了。

3)接到上面第2点,比如当我要实现用户的积分扣除功能。流程逻辑应该如下吧:

<code>1.先检测用户当前的积分是否充足?如果不充足失败且提示。
2.执行积分扣除
3.成功写入积分变更日志
</code>

像第3点这样的,该写在那个文件,特别让人疑惑 /models/Member.php 还是 /models/MemberQuery.php 还是 /components/Member/ScoresUse.php

4)如果真的像 【积分扣除】【用户封禁】这样的功能都制作成单独的组件components,那么ActiveRecord models那么岂不就真的就只剩下第2点里面说的这一段内容的?另外如果真的是这样,那岂不component 变得异常的庞大,但问题是执行【积分扣除】【用户封禁】这样的操作,不是单独某个表的,如果放到 /models/Member.php 里面去执行,需要调用额外的其他表,显然又不符合规范,显得很混乱。

5)比如 【积分扣除】【用户封禁】这样的操作必须可以让正在登陆用户自行调用,又可以让登陆的管理员自行登陆,所以,似乎归类到 model来说完全不适合? 归类到 component 却又还不如直接用 function 单独函数更方便?比如执行 【积分扣除变更】功能:

<code>php</code><code>/**
 * @description 操作用户积分!
 * @param $mid
 * @param $jftype
 * @param string $tips
 * @param null $jfValue2
 * @return bool
 */
function log_jifen_change($mid, $jftype, $tips = '', $jfValue2 = null)
{
    global $dsql;

    $jfvalue = $jfValue2 && is_numeric($jfValue2) ? $jfValue2 : jifen_value($jftype);

    if ($dsql->ExecuteNoneQuery2("UPDATE #@__member SET scores=scores+'$jfvalue' WHERE mid='" . $mid . "' ")) {

        $rs = $dsql->GetOne("SELECT `scores` FROM `#@__member` WHERE `mid`='{$mid}' ");
        $scoresLeft = $rs['scores'];

        $setarr = array(
            'mid'     => $mid, //会员ID
            'jftype'  => $jftype, //积分代码
            'jftime'  => time(), //操作时间
            'jfvalue' => $jfvalue, //本次变更积分
            'tips'    => $tips, //提示内容
            'jfleft'  => $scoresLeft, //剩余的积分
        );

        $dsql->ExecuteNoneQuery("INSERT INTO gk_member_jflog SET " . MkSetSql($setarr));

        return $scoresLeft;
    }

    return false;
}

</code>

PHP中什么时候该用 component 什么时候该用 model?特别让人迷惑。。。

真是,一下问这么多问题好难回答。

  1. 先说说什么时候继承 Model 什么时候继承 ActiveRecord?

当一个表单是操作多个表单的时候,建议你新建一个 From,From 只能继承 Model,每个表都要生成 Model,Model 都继承 ActiveRecord。

  1. component 与 model 的区别到底是在哪里?

我认为他们两个没什么关系啊,component 是组件,model 一般映射一个表单或者一个数据库表。

如果你的积分业务比较多,而又比较复杂你可以写成事件,其他地方调用。

最后安利一下:https://github.com/forecho/awesome-yii2

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use