版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Doctrine2featuresalightweighteventsystemthatispartoftheCommonpackage.Doctrineusesittodispatchsystemevents,mainlylifecycleevents.YoucanalsouseitforyourowncustomTheEventTheeventsystemiscontrolledbytheEventManager.ItisthecentralpointofDoctrine’seventlistenersystem.Listenersareregisteredonthemanagerandeventsaredispatchedthroughthemanager.9.9.1系$evm=newNowwecanaddsomeeventlistenerstothe$evm.Let’screateaTestEventclasstoyaroundclass{constpreFoo='preFoo';constpostFoo='postFoo';privatepublic$preFooInvoked=false;public {$evm->addEventListener(array(self::preFoo,self::postFoo),}publicfunctionpreFoo(EventArgs{$this->preFooInvoked=}publicfunctionpostFoo(EventArgs{$this->postFooInvoked=}}//Createanew$test=newEventscanbedispatchedbyusingthedispatchEvent()$evm-$evm-$evm->removeEventListener(array(self::preFoo,self::postFoo),TheDoctrine2eventsystemalsohasasimpleconceptofeventsubscribers.WecandefineimplementsagetSubscribedEvents()methodwhichreturnsanarrayofeventsitshouldbesubscribedto.Doctrne2系统也有一个简单的时间订阅的概念。我们可以定义一个简单的esEvenSuscriber类,它实现自DocrneComonvenubscrber接口,并且实现一个getubsrbedEvent()方法,此方法返回一个应该被订阅的的数组。classTestEventSubscriberimplements{public$preFooInvoked=publicfunction{$this->preFooInvoked=}publicfunction{return}}$eventSubscriber=new$evm-TheThearraytoreturninthegetSubscribedEventsmethodisasimplearraywiththevaluestheeventnames.Thesubscribermusthaveamethodthatisnamedexactlylikethe Nowwhenyoudispatchanevent,anyeventsubscriberswillbenotifiedforthat$evm-Nowyoucantestthe$eventSubscriberinstancetoseeifthepreFoo()methodwasif($eventSubscriber-{echo'prefoo}NamingEventsbeingusedwiththeDoctrine2EventManagerarebestnamedwithcamelcaseandthevalueofthecorrespondingconstantshouldbethenameoftheconstantitself,evenwithspelling.Thishasseveralreasons:Itiseasytoread.EachmethodwithinanEventSubscriberisnamedafterthecorrespondingconstant’svalue.Iftheconstant’snameandvaluedifferitcontradictstheintentionofusingtheconstantandmakesyourcodehardertomaintain.AnexampleforacorrectnotationcanbefoundintheexampleTestEventLifecycleTheEntityManagerandUnitOfWorktriggerabunchofeventsduringthelife-timeoftheirregisteredpreRemove-ThepreRemoveeventoccursforagivenentitybeforetherespectiveEntityManagerremoveoperationforthatentityisexecuted.ItisnotcalledforaDQLDELETEstatement.postRemove-ThepostRemoveeventoccursforanentityaftertheentityhasbeendeleted.Itwillbeinvokedafterthedatabasedeleteoperations.ItisnotcalledforaDQLDELETEstatement.prePersist-TheprePersisteventoccursforagivenentitybeforetherespectivepersistoperationforthatentityisexecuted.Itshouldbenotedthatthiseventisonlytriggeredoninitialpersistofanentity(i.e.itdoesnottriggeronfutureupdates).postPersist-ThepostPersisteventoccursforanentityaftertheentityhasbeenmadepersistent.Itwillbeinvokedafterthedatabaseinsertoperations.GeneratedprimarykeyvaluesareavailableinthepostPersistevent.preUpdate-ThepreUpdateeventoccursbeforethedatabaseupdateoperationstoentitydata.ItisnotcalledforaDQLUPDATEstatement.postUpdate-ThepostUpdateeventoccursafterthedatabaseupdateoperationstoentitydata.ItisnotcalledforaDQLUPDATEstatement.postLoad-ThepostLoadeventoccursforanentityaftertheentityhasbeenloadedintothecurrentEntityManagerfromthedatabaseoraftertherefreshoperationhasbeenappliedtoit.loadClassMetadata-TheloadClassMetadataeventoccursafterthemapmetadataforaclasshasbeenloadedfromamapsource(annotations/xml/yaml).ThiseventisnotalifecycleonClassMetadataNotFound-Loadingclassmetadataforaparticularrequestedclassnamefailed.Manipulatingthegiveneventargsinstanceallowsprovidingfallbackmetadataevenwhennoactualmetadataexistsorcouldbefound.Thiseventisnotalifecyclecallback.preFlush-ThepreFlusheventoccursattheverybeginningofaflushoperation.Thiseventisnotalifecyclecallback.onFlush-TheonFlusheventoccursafterthechange-setsofallmanagedentitiesarecomputed.Thiseventisnotalifecyclecallback.postFlush-ThepostFlusheventoccursattheendofaflushoperation.Thiseventisnotalifecyclecallback.onClear-TheonCleareventoccurswhentheEntityManager#clear()operationisinvoked,afterallreferencestoentitieshavebeenremovedfromtheunitofwork.ThiseventisnotalifecyclepreFlush- onFlush-onFlush postFlush- onClear-onClear yafterobjectsarebeinghydrated,andthereforeassociationsarenotguaranteedtobeinitialized.Itisnotsafetocombineusageof 注意,当使用te(),postLoadNotethatthepostRemoveeventoranyeventstriggeredafteranentityremovalcanreceivean incaseyouhaveconfiguredanentitytocascaderemoveInthiscase,youshouldloadyourself intheassociatedpre .YoucanaccesstheEventconstantsfromtheEventsclassintheORMechoEvents::preUpdate;ThesecanbehookedintobytwodifferenttypesofeventLifecycleCallbacksaremethodsontheentityclassesthatarecalledwhentheeventistriggered.Asofv2.4theyreceivesomekindofEventArgsinstance.LifecycleEventListenersandSubscribersareclasseswithspecificcallbackmethodsthatTheEventArgsinstancereceivedbythelistenergivesaccesstotheentity,EntityManagerand AllAllLifecycleeventsthathappenduringtheflush()ofanEntityManagerhaveveryconstraintsontheallowedoperationsthatcanbeexecuted.PleasereadtheImplementingEventListenerssectionverycarefullytounderstandwhichoperationsareallowedinlifecycle限定条件。阅读ImplementingEventListenersLifecycleLifecycleCallbacksaredefinedonanentityclass.Theyallowyoutotriggercallbackswheneveraninstanceofthatentityclassexperiencesarelevantlifecycleevent.Morethanonecallbackcanbedefinedforeachlifecycleevent.LifecycleCallbacksarebestusedforsimpleoperationsspecifictoaparticularentityclass’slifecycle.classUser{//*@Column(type="string",publicprivate$createdAt;/**@PrePersistpublicfunction{$this->createdAt=date('Y-m-d}/**@PrePersistpublicfunction{$this->value='changedfromprePersist}/**@PostPersistpublicfunction{$this->value='changedfrompostPersist}/**@PostLoadpublicfunction{$this->value='changedfrompostLoad}/**@PreUpdatepublicfunction{$this->value='changedfrompreUpdate}}Notethatthemethodssetaslifecyclecallbacksneedtobepublicand,whenusingtheseannotations,youhavetoapplythe@HasLifecycleCallbacksmarkerannotationontheentityclass.IfyouwanttoregisterlifecyclecallbacksfromYAMLorXMLyoucandoitwiththetype:#type:string(50)prePersist:[doStuffOnPrePersist,doOtherStuffOnPrePersist]postPersist:[doStuffOnPostPersist]InYAMLthekeyofthelifecycleCallbacksentryistheeventthatyouaretriggeringonandthevalueisthemethod(ormethods)tocall.TheallowedeventtypesaretheoneslistedinthepreviousLifecycleEventssection.XMLwouldlooksomethinglike<?xmlversion="1.0"encoding="UTF-<doctrine-mapxmlns="xmlns:xsi="/Users/robo/dev/php/Doctrine/doctrine-map<entity<lifecycle-<lifecycle-callbacktype="prePersist"<lifecycle-callbacktype="postPersist"</lifecycle-</doctrine-mapInXMLthetypeofthelifecycle-callbackentryistheeventthatyouaretriggeringonandthemethodisthemethodtocall.TheallowedeventtypesaretheoneslistedinthepreviousLifecycleEventsWhenusingYAMLorXMLyouneedtoremembertocreatepublicmethodstomatchthecallbacknamesyouneedtobedefinedonyourUsermodel.//class{//publicfunction{//}publicfunction{//}publicfunction{//}}LifecycleCallbacksEventNewinversionSince2.4thetriggeredeventisgiventothelifecycle-//class{publicfunctionpreUpdate(PreUpdateEventArgs{ ($event- //Dosomethingwhentheusernameis}}}ListeningandsubscribingtoLifecycleLifecycleeventlistenersaremuchmorepowerfulthanthesimplelifecyclecallbacksthataredefinedontheentityclasses.Theysitatalevelabovetheentitiesandallowyoutoimplementre-usablebehaviorsacrossdifferententityclasses.NotethattheyrequiremuchmoredetailedknowledgeabouttheinnerworkingsoftheEntityManagerandUnitOfWork.PleasereadtheImplementingEventListenerssectioncarefullyifyouaretryingtowriteyourownlistener.Foreventsubscribers,therearenosurprises.TheydeclarethelifecycleeventstheirgetSubscribedEventsmethodandprovidepublicmethodsthatexpecttherelevantarguments.Alifecycleeventlistenerlookslikethefollowing:ImplementingEventListenersuseclass{publicfunctionpreUpdate(LifecycleEventArgs{$entity=$args-$entityManager=$args-//perhapsyouonlywanttoactonsome"Product"entityif($entityinstanceofProduct){//dosomethingwiththe}}}AlifecycleeventsubscribermaylookslikeuseuseuseclassMyEventSubscriberimplements{publicfunction{array(Events::postUpd}publicfunctionpostUpdate(LifecycleEventArgs{$entity=$args-$entityManager=$args-//perhapsyouonlywanttoactonsome"Product"entityif($entityinstanceofProduct){//dosomethingwiththe}}LifecycleLifecycleeventsaretriggeredforallentities.Itistheresponsibilityofthelistenersandsubscriberstocheckiftheentityisofatypeitwantstohandle. Toregisteraneventlistenerorsubscriber,youhavetohookitintotheEventManagerthatispassedtotheEntityManagerfactory:$eventManager=new$eventManager->addEventListener(array(Events::preUpdate),new$eventManager->addEventSubscriber(new$entityManager=EntityManager::create($dbOpts,$config,YoucanalsoretrievetheeventmanagerinstanceaftertheEntityManagerwas$entityManager->getEventManager()->addEventListener(array(Events::preUpdate),new$entityManager->getEventManager()->addEventSubscriber(newImplementingEventThissectionexinswhatisandwhatisnotallowedduringspecificlifecycleeventsoftheUnitOfWork.AlthoughyougetpassedtheEntityManagerinalloftheseevents,youhavetofollowtheserestrictionsverycarefullysinceoperationsinthewrongeventmayproducelotsofdifferenterrors,suchasinconsistentdataandlostupdates/persists/removes.Forthedescribedeventsthatarealsolifecyclecallbackeventstherestrictionsapplyaswell,withtheadditionalrestrictionthat(priortoversion2.4)youdonothaveaccesstotheEntityManagerorUnitOfWorkAPIsinsidetheseevents.TherearetwowaysfortheprePersisteventtobetriggered.OneisobviouslywhenyoucallEntityManager#persist().Theeventisalsocalledforallcascadedassociations.ThereisanotherwayforprePersisttobecalled,insidetheflush()methodwhenchangestoassociationsarecomputedandthisassociationismarkedascascadepersist.AnynewentityfoundduringthisoperationisalsopersistedandprePersistcalledonit.Thisiscalled“persistencebyreachability”.InbothcasesyougetpassedaLifecycleEventArgsinstancewhichhasaccesstotheentityandtheentityThefollowingrestrictionsapplytoIfyouareusingaPrePersistIdentityGeneratorsuchassequencestheIDvaluewillNOTbeavailablewithinanyPrePersistevents.DoctrinewillnotrecognizechangesmadetorelationsinaprePersistevent.Thisincludesmodificationstocollectionssuchasadditions,removalsorrecement.ThepreRemoveeventiscalledoneveryentitywhenitspassedtotheEntityManager#remove()method.Itiscascadedforallassociationsthataremarkedascascadedelete.TherearenorestrictionstowhatmethodscanbecalledinsidethepreRemoveevent,exceptwhentheremovemethoditselfwascalledduringaflushoperation.insideitslisteners.classPreFlushExampleListener{publicfunctionpreFlush(PreFlushEventArgs{//}}OnFlushisaverypowerfulevent.ItiscalledinsideEntityManager#flush()afterthechangestoallthemanagedentitiesandtheirassociationshavebeencomputed.Thismeans,theonFlusheventhasaccesstothesetsof:EntitiesscheduledforinsertEntitiesscheduledforupdateEntitiesscheduledforremovalCollectionsscheduledforupdateCollectionsscheduledforremovalTomakeuseoftheonFlusheventyouhavetobefamiliarwiththeinternalUnitOfWorkAPI,whichgrantsyouaccesstothepreviouslymentionedsets.Seethisexample: class{publicfunctiononFlush(OnFlushEventArgs{$em=$eventArgs-$uow=$em-foreach($uow->getScheduledEntityInsertions()as$entity)}foreach($uow->getScheduledEntityUpdates()as$entity)}foreach($uow->getScheduledEntityDeletions()as$entity)}foreach($uow->getScheduledCollectionDeletions()as$col)}foreach($uow->getScheduledCollectionUpdates()as$col)}}}ThefollowingrestrictionsapplytotheonFlushIfyoucreateandpersistanewentityinonFlush,thencallingEntityManager#persist()isnotenough.Youhavetoexecuteanadditionalcallto$unitOfWork->computeChangeSet($classMetadata,$entity).Changingprimitivefieldsorassociationsrequiresyoutoexplicitlytriggera putationofthechangesetoftheaffectedentity.Thiscanbedonebycalling$unitOfWork- 的调用$unitOfWork->computChangeSet($classMetadata,$entity) itslisteners.classPostFlushExampleListener{publicfunctionpostFlush(PostFlushEventArgs{//}}PreUpdateisthemostrestrictivetouseevent,sinceitiscalledrightbeforeanupdatestatementiscalledforanentityinsidetheEntityManager#flush()method.Changestoassociationsoftheupdatedentityareneverallowedinthisevent,sinceDoctrineguaranteetocorrectlyhandlereferentialintegrityatthispointoftheflushoperation.Thiseventhasapowerfulfeaturehowever,itisexecutedwithaPreUpdateEventArgsinstance,whichcontainsareferencetothecomputedchange-setofthisentity.Thismeansyouhaveaccesstoallthefieldsthathavechangedforthisentitywiththeiroldandnewvalue.ThefollowingmethodsareavailableonthePreUpdateEventArgs:getEntity()togetaccesstotheactualgetEntityChangeSet()togetacopyofthechangesetarray.Changestothisreturnedarraydonotaffectupdating.getOldValue($fieldName)andgetNewValue($fieldName)toaccessthevaluesofafield.setNewValue($fieldName,$value)tochangethevalueofafieldtobeupdated.Asimpleexampleforthiseventlooks()hasChangedField($fieldName)检查是否当前实体的给定字段名修改了。getOldValue($fieldName)和getNewValue($fieldName)来进入一个字段的值。setNewValue($fieldName,$value)来修改用来更新字段的值。class{publicfunctionpreUpdate(PreUpdateEventArgs{if($eventArgs->getEntity()instanceofUser)if($eventArgs->hasChangedField('name')&&$eventArgs->getNewValue('name')=='Alice')$eventArgs->setNewValue('name',}}}}Youcouldalsousethislistenertoimplementvalidationofallthefieldsthathavechanged.Thisismoreefficientthanusingalifecyclecallbackwhenthereareexpensivevalidationstocall:class{publicfunctionpreUpdate(PreUpdateEventArgs{if($eventArgs->getEntity()instanceofAccount) $this->validateCreditCard($eventArgs-}}}privatefunction{//throwanexceptiontointerruptflushevent.Transactionwillberolled}}RestrictionsforthisChangestoassociationsofthepassedentitiesarenotrecognizedbytheflushoperationanymore.Changestofieldsofthepassedentitiesarenotrecognizedbytheflushoperationanymore,usethecomputedchange-setpassedtotheeventtomodifyprimitivefieldvalues,e.g.use$eventArgs-AnycallstoEntityManager#persist()orEntityManager#remove(),evenincombinationwithUnitOfWorkAPIarestronglydiscouragedanddon’tworkasexpectedoutsidetheflush,);postUpdate,postRemove,ThethreeposteventsarecalledinsideEntityManager#flush().Changesinherearenotrelevanttothepersistenceinthedatabase,butyoucanusetheseeventstoalternon-persistableitems,likenon-mappedfields,loggingorevenassociatedclassesthataredirectlymappedbyDoctrine.ThiseventiscalledafteranentityisconstructedbytheEntityNewinversionAnentitylistenerisalifecyclelistenerclassusedforanTheentitylistener’smapmaybeappliedtoanentityclassormappedAnentitylistenerisdefinedbymaptheentityclasswiththecorrespondingmap2.4 namespace/**@Entity@EntityListeners({"UserListener"})classUser{ EntitylistenersAnEntityListenercouldbeanyclass,bydefaultitshouldbeaclasswithano-argDifferentfromImplementingEventListenersanEntityListenerisinvokedjusttothespecifiedAnentitylistenermethodreceivestwoarguments,theentityinstanceandthelifecycleevent.Thecallbackmethodcanbedefinedbynamingconventionorspecifyingamethodmap.Whenalistenermapisnotgiventheparserwillusethenamingconventiontolookforamatchingmethod,e.g.itwilllookforapublicpreUpdate()methodifyouarelisteningtothepreUpdateWhenalistenermapisgiventheparserwillnotlookforanymethodsusingthe 当一 preUpdate,它将找一个publicpreUpdate()当一 class{publicfunctionpreUpdate(User$user,PreUpdateEventArgs{//Dosomethingonpre}}Todefineaspecificeventlistenermethod(onethatdoesnotfollowthenamingconvention)youneedtomapthelistenermethodusingtheeventtypemap:class{/**@PrePersistpublicfunctionprePersistHandler(User$user,LifecycleEventArgs$event){//.../**@PostPersistpublicfunctionpostPersistHandler(User$user,LifecycleEventArgs$event){//.../**@PreUpdatepublicfunctionpreUpdateHandler(User$user,PreUpdateEventArgs$event){//.../**@PostUpdatepublicfunctionpostUpdateHandler(User$us
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 麻醉药的使用
- 识字4《田家四季歌》课件(共22张)
- 15 背影 课件(共45张)
- Sampsone-B-生命科学试剂-MCE
- 隧洞突泥注浆扩散方案
- 冻土公路热棒桩基布设定位施工方案
- 不孕症(辅助生殖技术)患者的护理查房
- 自然地理学论文答辩模板
- 紫色炫酷霓虹灯夜市烧烤模板
- 人体胚胎发育辅助生殖课件
- 2026 年班组建设工作回顾凝聚团队干事创业力量课件
- 2026年临沧市公安局临翔分局招聘警务辅助人员(30人)笔试备考题库及答案解析
- 2026年中国哲学思想知识竞赛模拟试卷带答案
- 2026年体检中心医疗废物处理管理制度范本
- 2027年备考军队文职人员招聘之军队文职法学通关试题库(有答案)
- 数智化组织管理 课件全套 第1-11章 数智化组织管理导论 - -数智化情境下的组织变革
- 6.2搭建立体大楼 课件 北师大版数学四年级上册
- 《CPPC1090河湖生态环境修复治理验收规范》
- 2026年高级职业培训师(三级)职业资格鉴定考试题库(新版)
- 2026年甘孜州事业单位考试真题及答案
- 2025年贵阳市乌当区社区工作者招聘笔试试题及答案详解
评论
0/150
提交评论