![events件你也可以使用它來(lái)自定義_第1頁(yè)](http://file4.renrendoc.com/view/c232347309100ad4f7d6016c677c8a91/c232347309100ad4f7d6016c677c8a911.gif)
![events件你也可以使用它來(lái)自定義_第2頁(yè)](http://file4.renrendoc.com/view/c232347309100ad4f7d6016c677c8a91/c232347309100ad4f7d6016c677c8a912.gif)
![events件你也可以使用它來(lái)自定義_第3頁(yè)](http://file4.renrendoc.com/view/c232347309100ad4f7d6016c677c8a91/c232347309100ad4f7d6016c677c8a913.gif)
![events件你也可以使用它來(lái)自定義_第4頁(yè)](http://file4.renrendoc.com/view/c232347309100ad4f7d6016c677c8a91/c232347309100ad4f7d6016c677c8a914.gif)
![events件你也可以使用它來(lái)自定義_第5頁(yè)](http://file4.renrendoc.com/view/c232347309100ad4f7d6016c677c8a91/c232347309100ad4f7d6016c677c8a915.gif)
版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
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系統(tǒng)也有一個(gè)簡(jiǎn)單的時(shí)間訂閱的概念。我們可以定義一個(gè)簡(jiǎn)單的esEvenSuscriber類,它實(shí)現(xiàn)自DocrneComonvenubscrber接口,并且實(shí)現(xiàn)一個(gè)getubsrbedEvent()方法,此方法返回一個(gè)應(yīng)該被訂閱的的數(shù)組。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 注意,當(dāng)使用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- 的調(diào)用$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)檢查是否當(dāng)前實(shí)體的給定字段名修改了。getOldValue($fieldName)和getNewValue($fieldName)來(lái)進(jìn)入一個(gè)字段的值。setNewValue($fieldName,$value)來(lái)修改用來(lái)更新字段的值。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 當(dāng)一 preUpdate,它將找一個(gè)publicpreUpdate()當(dāng)一 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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 八年級(jí)英語(yǔ)下冊(cè) Unit 4 單元綜合測(cè)試卷(人教陜西版 2025年春)
- 2024-2025學(xué)年山東省煙臺(tái)市棲霞市四年級(jí)(上)期末數(shù)學(xué)試卷
- 高一化學(xué)1月月考試題解析版
- 2025年重組載體疫苗合作協(xié)議書(shū)
- 2025年買方信貸合作協(xié)議(三篇)
- 2025年個(gè)人的租房合同樣本(三篇)
- 2025年億家益公司蕪湖加盟加盟店加盟合同(三篇)
- 2025年個(gè)人購(gòu)買汽車合同(2篇)
- 2025年二人合伙經(jīng)營(yíng)協(xié)議簡(jiǎn)單版(4篇)
- 2025年中外合資企業(yè)勞務(wù)合同(2篇)
- 渤海大學(xué)《大數(shù)據(jù)分析與實(shí)踐》2023-2024學(xué)年期末試卷
- 2024版2024年《咚咚鏘》中班音樂(lè)教案
- GA 2139-2024警用防暴臂盾
- DL∕T 5810-2020 電化學(xué)儲(chǔ)能電站接入電網(wǎng)設(shè)計(jì)規(guī)范
- 北京三甲中醫(yī)疼痛科合作方案
- QCT957-2023洗掃車技術(shù)規(guī)范
- 新外研版高中英語(yǔ)選擇性必修1單詞正序英漢互譯默寫(xiě)本
- 自愿斷絕父子關(guān)系協(xié)議書(shū)電子版
- 2023年4月自考00504藝術(shù)概論試題及答案含解析
- 美麗的大自然(教案)2023-2024學(xué)年美術(shù)一年級(jí)下冊(cè)
- 成都特色民俗課件
評(píng)論
0/150
提交評(píng)論