概述
行为(Behavior)是ThinkPHP扩展机制中比较关键的一项扩展,行为既可以独立调用,也可以绑定到某个标签中进行侦听,官方提出的CBD模式中行为也占了主要的地位,可见行为在ThinkPHP框架中意义非凡。
这里指的行为是一个比较抽象的概念,你可以想象成在应用执行过程中的一个动作或者处理,在框架的执行流程中,各个位置都可以有行为产生,例如路由检测是一个行为,静态缓存是一个行为,用户权限检测也是行为,大到业务逻辑,小到浏览器检测、多语言检测等等都可以当做是一个行为,甚至说你希望给你的网站用户的第一次访问弹出Hello,world!这些都可以看成是一种行为,行为的存在让你无需改动框架和应用,而在外围通过扩展或者配置来改变或者增加一些功能。
而不同的行为之间也具有位置共同性,比如,有些行为的作用位置都是在应用执行前,有些行为都是在模板输出之后,我们把这些行为发生作用的位置称之为标签(位),当应用程序运行到这个标签的时候,就会被拦截下来,统一执行相关的行为,类似于AOP编程中的“切面”的概念,给某一个切面绑定相关行为就成了一种类AOP编程的思想。
系统标签位
系统核心提供的标签位置包括下面几个(按照执行顺序排列):
在每个标签位置,可以配置多个行为定义,行为的执行顺序按照定义的顺序依次执行。除非前面的行为里面中断执行了(某些行为可能需要中断执行,例如检测机器人或者非法执行行为),否则会继续下一个行为的执行。
除了这些系统内置标签之外,开发人员还可以在应用中添加自己的应用标签,例如我们给应用的公共Action类CommonAction添加一个action_init标签位。
Public function _initialize(){
tag(‘action_init’); // 添加action_init 标签
}
}
注意:tag函数用于设置某个标签位,可以传入并且只接受一个参数,如果需要传入多个参数,请使用数组,该参数为引用传值,所以只能传入变量。
核心行为
新版系统的很多核心功能也是采用行为扩展组装的,虽然在开发过程中可能感觉不到这种变化,但正是由于这种架构设计的改变,让新版变得更加灵活和易扩展,这是一个里程碑式的改变,对于满足项目日益纷繁复杂的需求和定制底层框架提供了更多的方便和可能性。
框架核心内置的行为包括如下:
行为定义
行为类的命名采用:行为名称(驼峰法,首字母大写)+Behavior行为类的定义方式如下:
// 行为参数定义
protected $options = array(
‘test_param’ => false, // 行为参数 会转换成TEST_PARAM配置参数
);
// 行为扩展的执行入口必须是run
public function run(&$params){
if(C(‘TEST_PARAM’)) {
echo ‘RUNTEST BEHAVIOR ‘.$params;
}
}
}
行为类必须继承Behavior类,并且必须定义执行入口方法run(&$params);由于行为的调用机制影响,run方法不需要任何返回值,所有返回都通过引用返回。每个行为类可以定义options属性,该属性中的参数会自动转换成单独配置参数,也就是说该参数可以用全局的C方法直接读取或者修改,同时也意味着行为中定义的options参数只是提供一个默认值,你完全可以在配置文件中或者使用C方法动态配置生效,而不需要手动传入行为类。这是Behavior类提供的方便和全局配置对接的一个特性,当然你完全可以不依赖这个特性。
因此,上面的run方法实现也可以更改为:
if($this->test_param) {
echo ‘RUNTEST BEHAVIOR ‘.$params;
}
}
run方法的参数只有一个,但支持传入数组。
行为类是支持自动加载的,其放置的位置可以包括如下位置,可以根据需要自行选择:
官方扩展包的行为扩展都位于Extend/Behavior/目录下面。
行为绑定
行为定义完成后,就需要绑定到某个标签位置才能生效,否则是不会执行的。
我们需要在项目的行为定义文件tags.php文件中进行行为和标签的位置定义,格式如下:
‘标签名称’=>array(‘行为名1′,’行为名2’,…),
);
标签名称包括我们前面列出的系统标签和应用中自己定义的标签名称,比如你需要在app_init标签位置定义一个CheckLangBehavior行为类的话,可以使用:
‘app_init’=>array(‘CheckLang’),
);
可以给一个标签位定义多个行为,行为的执行顺序就是定义的先后顺序,例如:
‘app_init’=>array(‘CheckLang’,’CronRun’),
);
默认情况下tags.php中定义的行为会并入系统行为一起执行,也就是说如果系统的行为定义中app_init标签中已经定义了其他行为,则会首先执行系统行为扩展中定义的行为,然后再执行项目行为中定义的行为,如果你希望项目tags中定义的行为完全替换系统的行为扩展,可以使用:
‘app_init’=>array(‘CheckLang’,’CronRun’,’_overlay’=>1),
);
应用行为的定义没有限制,你可以把一个行为绑定到多个标签位置执行,例如:
‘app_begin’=>array(‘Test’), // 在app_begin 标签位添加Test行为
‘app_end’=>array(‘Test’), // 在app_end 标签位添加Test行为
);
为了避免混淆,自定义的行为扩展尽量不要和核心的行为扩展重名。
除了定义tags行为配置文件之外,框架还提供了动态添加行为到标签位的方法,例如我们可以使用下面的方式添加Test行为到app_end标签位,而无需在tags文件中添加定义:
表示把Test行为添加到app_end标签位的最后,你可以把这个代码放到项目的公共函数文件中甚至直接放到行为类的最后(如果你确定这个行为扩展只有你的项目会用到的话)。
单独执行
有时候,行为的调用不一定要放到标签才能调用,如果需要的话,我们可以在控制器中直接调用行为。例如,我们可以把用户权限检测封装成一个行为类,例如:
// 行为参数定义
protected $options = array(
‘USER_AUTH_ON’ =>false, // 是否开启用户认证
‘USER_AUTH_ID’ => ‘user_id’, // 定义用户的id为权限认证字段
);
// 行为扩展的执行入口必须是run
public function run(&$return){
if(C(‘USER_AUTH_ON ‘)) {
// 进行权限认证逻辑 如果认证通过 $return = true;
// 否则用halt输出错误信息
}
}
定义了AuthCheck行为后,然后在_initialize方法中直接用下面的方式调用:
注意:因为这种方式的行为调用需要在相关位置添加代码,所以一般只有在应用代码才直接使用B方法调用。
总结
说了这么多,只是让你了解ThinkPHP中的行为的概念和运行机制,至于如何用好行为,以及怎么封装行为和定义标签还需要多实践了。相信很多熟悉ThinkPHP的开发者一定可以通过行为扩展来更方便的给框架增加功能了。
波比源码 » ThinkPHP3.1快速入门(22)行为
cost levaquin 250mg levaquin us
indomethacin for sale online trimox 250mg cost trimox 500mg cheap
cialis 5mg without prescription non prescription cialis viagra fast shipping
accutane 10mg uk purchase amoxicillin for sale buy ivermectin 2mg
brand fluvoxamine 50mg fluvoxamine 50mg without prescription buy glucotrol online
generic furosemide 40mg order lasix pill oral plaquenil 400mg
cialis 40mg ca otc cialis viagra 150mg for sale
losartan tablet buy topamax 100mg for sale buy topamax 200mg online cheap
flagyl 200mg over the counter order bactrim 960mg pill order bactrim 480mg online
sildenafil uk sildenafil online order purchase tadalafil online cheap
deltasone over the counter buy isotretinoin 20mg without prescription amoxicillin 1000mg generic
sildenafil 50mg cheap tamoxifen 10mg tablet budesonide buy online
naproxen over the counter order naproxen 500mg generic prevacid price
clarithromycin canada clonidine price buy antivert 25 mg without prescription
spiriva 9 mcg for sale purchase hytrin generic hytrin 5mg uk
order singulair 10mg sale brand sildenafil 50mg viagra 150mg for sale
order actos for sale viagra 50mg cheap order viagra 50mg pill
cialis 10mg ca Generic cialis usa purchase cialis pills
ivermectin covid avlosulfon 100mg cheap dapsone medication
Le fonctionnement est très simple pour ces machines, car vous devez remplir les pochettes par exemple avec les restes de table ou les aliments de votre choix. Vous positionnez ensuite l’ouverture au niveau de cette machine qui s’occupe de supprimer tout l’air. Le format est identique à celui utilisé pour les fameuses housses sous vide pour ranger toutes les affaires du quotidien comme les vêtements et les couettes qui seront également moins encombrantes dans les placards. Conçus pour le stockage, la présentation et l’envoi de vos denrées, nos réfrigérateurs, congélateurs, machine à glaçons ou encore arrières de bar trouverons leur place dans votre établissement. Idéalement conçus pour les professionnels, tous nos équipements frigorifiques sont robustes et fiables avec la possibilité de changer les pièces défectueuses.
https://front-wiki.win/index.php?title=Nouveau_casino_sans_depot
Jouer sur un casino en ligne au Canada peut se faire parfois sans que vous ayez forcément à procéder à un versement. Un casino en ligne bonus sans dépôt Canada est en effet un cadeau sous forme d’argent cash qui peut être misé sur une sélection de jeux d’argent en ligne et qui vous permet de conserver les fonds que vous remportez. Il est rare dans l’univers du casino online, mais les utilisateurs l’adorent. Les jeux de Jackpot City sont produits par Microgaming et Evolution Gaming. Ces deux groupes sont connus pour mettre à disposition de leurs partenaires affiliés des jeux haut de gamme. À ce jour les logiciels de Jackpot City sont les plus performants du domaine des casinos à distance. Ils sont ainsi les garants d’une expérience réelle de jeu tout en offrant des vraies possibilités de gagner. Globalement c’est une immersion dans une maison de jeu d’envergure.
order adalat pill buy allegra sale order allegra 120mg generic
altace online order purchase glimepiride sale order etoricoxib 60mg online cheap
online assignment writer purchase azulfidine online cheap buy azulfidine 500mg generic
When the game kicks off, our NFL Livescores track the game and show who’s winning and losing during the contest. When the game reaches halftime, the NFL Scoreboard become more popular since the Line Movements present the second-half odds. Savvy bettors looking to chase or press their bets always come here first to see the odds on the final two quarters of action. See historical standings on any date NFL scores aren’t just a way to notify you with regards to the status of your favorite team’s action tonight. NFL scores also help you stay in touch with your moneyline bets and your OVER/UNDER football wagers. Odds Shark refreshes its NFL scoreboard with every touchdown so you can celebrate or drown in your sorrow based on the action on the field. What’s more, is you can see how your side or total wagers are shaping out at your preferred NFL betting sites.
https://wiki-saloon.win/index.php?title=Laliga_live_results
India vs Sri Lanka | IND vs SL 1st T20I LIVE | Pre-Match Analysis India vs England World Cup 2019 Live Updates: Your browser is out of date or some of its features are disabled, it may not display this website or some of its parts correctly. A productive last over for AFG as they smash 13 off Adil Rashid’s over. Can Ghani and Zadran get AFG to a good total? Score after 13 overs, AFG: 78/3 Sam Curran removes Ibrahim Zadran for 32. Afghanistan needs to accelerate to score a big total. Score after 12 overs, AFG: 65/3 Boland Park is a multi-purpose stadium in Paarl, South Africa. It is currently used… IDN vs KOR Dream11 Prediction, Player Stats & Pitch Report – 1st Match, ICC Men’s T20I WC EAP Qualifier B India vs Sri Lanka | IND vs SL 1st T20I LIVE | Mid-Innings
mesalamine sale irbesartan brand purchase avapro online cheap
benicar sale cost calan 240mg buy depakote online
acetazolamide 250mg without prescription isosorbide brand buy imuran 25mg for sale
order digoxin 250 mg generic order molnunat 200 mg online purchase molnunat generic
carvedilol for sale online buy amitriptyline online elavil 50mg oral
dapoxetine 90mg pills generic domperidone 10mg order generic domperidone 10mg
purchase doxycycline without prescription medrol price cost of medrol
order ropinirole online cheap order trandate for sale buy labetalol 100 mg online cheap
purchase fenofibrate fenofibrate online buy real viagra pills
buy generic nexium clarithromycin us furosemide online order
cialis 5mg pills Discount tadalafil no rx viagra 50mg drug
cialis tadalafil Cialis by mail buy best erectile dysfunction pills
glucophage usa order glucophage 500mg for sale buy tamoxifen for sale
prednisone 5mg us buy amoxicillin pills order amoxicillin 500mg
buy ventolin 2mg without prescription augmentin canada augmentin online