events件你也可以使用它来自定义_第1页
events件你也可以使用它来自定义_第2页
events件你也可以使用它来自定义_第3页
events件你也可以使用它来自定义_第4页
events件你也可以使用它来自定义_第5页
已阅读5页,还剩32页未读, 继续免费阅读

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论