Anda di halaman 1dari 4

6/20/2016

ModelViewController(MVC)InPHPTutorial

ModelViewController(MVC)InPHPTutorial
Themodelviewcontrollerpatternisthemostusedpatternfortodaysworldwebapplications.Ithasbeenused
forthefirsttimeinSmalltalkandthenadoptedandpopularizedbyJava.Atpresenttherearemorethana
dozenPHPwebframeworksbasedonMVCpattern.
DespitethefactthattheMVCpatternisverypopularinPHP,ishardtofindapropertutorialaccompaniedbya
simplesourcecodeexample.Thatisthepurposeofthistutorial.
TheMVCpatternseparatesanapplicationin3modules:Model,ViewandController:
Themodelisresponsibletomanagethedataitstoresandretrievesentitiesusedbyanapplication,usually
fromadatabase,andcontainsthelogicimplementedbytheapplication.
Theview(presentation)isresponsibletodisplaythedataprovidedbythemodelinaspecificformat.Ithas
asimilarusagewiththetemplatemodulespresentinsomepopularwebapplications,likewordpress,joomla,

Thecontrollerhandlesthemodelandviewlayerstoworktogether.Thecontrollerreceivesarequestfrom
theclient,invokesthemodeltoperformtherequestedoperationsandsendsthedatatotheView.Theview
formatsthedatatobepresentedtotheuser,inawebapplicationasanhtmloutput.
TheabovefigurecontainstheMVCCollaborationDiagram,wherethelinksanddependenciesbetweenfigures
canbeobserved:

Ourshortphpexamplehasasimplestructure,puttingeachMVCmoduleinonefolder:

Controller
Thecontrolleristhefirstthingwhichtakesarequest,parsesit,initializesandinvokethemodelandtakesthe
modelresponseandsendsittothepresentationlayer.ItspracticallytheliantbetweentheModelandtheView,
asmallframeworkwhereModelandViewarepluggedin.Inournaivephpimplementationthecontrolleris
implementedbyonlyoneclass,namedunexpectedlycontroller.Theapplicationentrypointwillbeindex.php.
Theindexphpfilewilldelegatealltherequeststothecontroller:
1.//index.phpfile
2.include_once("controller/Controller.php")
3.$controller=newController()
4.$controller>invoke()
OurControllerclasshasonlyonefunctionandtheconstructor.Theconstructorinstantiatesamodelclassand
whenarequestisdone,thecontrollerdecideswhichdataisrequiredfromthemodel.Thenitcallsthemodel
classtoretrievethedata.Afterthatitcallsthecorrespondingpassingthedatacomingfromthemodel.The
http://phphtml.net/tutorials/modelviewcontrollerinphp/

1/4

6/20/2016

ModelViewController(MVC)InPHPTutorial

codeisextremelysimple.Notethatthecontrollerdoesnotknowanythingaboutthedatabaseorabouthowthe
pageisgenerated.
1.include_once("model/Model.php")
2.classController{
3.public$model
4.publicfunction__construct()
5.{
6.$this>model=newModel()
7.}
8.publicfunctioninvoke()
9.{
10.if(!isset($_GET['book']))
11.{
12.//nospecialbookisrequested,we'llshowalistofallavailablebooks
13.$books=$this>model>getBookList()
14.include'view/booklist.php'
15.}
16.else
17.{
18.//showtherequestedbook
19.$book=$this>model>getBook($_GET['book'])
20.include'view/viewbook.php'
21.}
22.}
23.}
InthefollowingMVCSequenceDiagramyoucanobservetheflowduringahttprequest:

ModelandEntityClasses
TheModelrepresentsthedataandthelogicofanapplication,whatmanycallsbusinesslogic.Usually,its
responsiblefor:
storing,deleting,updatingtheapplicationdata.Generallyitincludesthedatabaseoperations,but
implementingthesameoperationsinvokingexternalwebservicesorAPIsisnotanunusualatall.
encapsulatingtheapplicationlogic.Thisisthelayerthatshouldimplementallthelogicoftheapplication.The
mostcommonmistakesaretoimplementapplicationlogicoperationsinsidethecontrollerorthe
view(presentation)layer.
Inourexamplethemodelisrepresentedby2classes:theModelclassandaBookclass.Themodeldoesnt
needanyotherpresentation.TheBookclassisanentityclass.ThisclassshouldbeexposedtotheViewlayer
andrepresentstheformatexportedbytheModelview.InagoodimplementationoftheMVCpatternonlyentity
classesshouldbeexposedbythemodelandtheyshouldnotencapsulateanybusinesslogic.Theirsolely
http://phphtml.net/tutorials/modelviewcontrollerinphp/

2/4

6/20/2016

ModelViewController(MVC)InPHPTutorial

purposeistokeepdata.DependingonimplementationEntityobjectscanbereplacedbyxmlorjsonchunkof
data.IntheabovesnippetyoucannoticehowModelisreturningaspecificbook,oralistofallavailablebooks:
1.include_once("model/Book.php")
2.classModel{
3.publicfunctiongetBookList()
4.{
5.//heregoessomehardcodedvaluestosimulatethedatabase
6.returnarray(
7."JungleBook"=>newBook("JungleBook","R.Kipling","Aclassicbook."),
8."Moonwalker"=>newBook("Moonwalker","J.Walker",""),
9."PHPforDummies"=>newBook("PHPforDummies","SomeSmartGuy","")
10.)
11.}
12.publicfunctiongetBook($title)
13.{
14.//weusethepreviousfunctiontogetallthebooksandthenwereturntherequestedone.
15.//inareallifescenariothiswillbedonethroughadbselectcommand
16.$allBooks=$this>getBookList()
17.return$allBooks[$title]
18.}
19.}
InourexamplethemodellayerincludestheBookclass.Inarealscenario,themodelwillincludealltheentities
andtheclassestopersistdataintothedatabase,andtheclassesencapsulatingthebusinesslogic.
1.classBook{
2.public$title
3.public$author
4.public$description
5.publicfunction__construct($title,$author,$description)
6.{
7.$this>title=$title
8.$this>author=$author
9.$this>description=$description
10.}
11.}

View(Presentation)
Theview(presentationlayer)isresponsibleforformatingthedatareceivedfromthemodelinaformaccessible
totheuser.Thedatacancomeindifferentformatsfromthemodel:simpleobjects(sometimescalledValue
Objects),xmlstructures,json,
Theviewshouldnotbeconfusedtothetemplatemechanismsometimestheyworkinthesamemannerand
addresssimilarissues.Bothwillreducethedependencyofthepresentationlayeroffromrestofthesystemand
separatesthepresentationelements(html)fromthecode.Thecontrollerdelegatesthedatafromthemodeltoa
specificviewelement,usuallyassociatedtothemainentityinthemodel.Forexampletheoperationdisplay
accountwillbeassociatedtoadisplayaccountview.Theviewlayercanuseatemplatesystemtorenderthe
htmlpages.Thetemplatemechanismcanreusespecificpartsofthepage:header,menus,footer,listsand
tables,.SpeakinginthecontextoftheMVCpattern
Inourexampletheviewcontainsonly2filesonefordisplayingonebookandtheotheronefordisplayingalist
ofbooks.
viewbook.php
1.<html>
http://phphtml.net/tutorials/modelviewcontrollerinphp/

3/4

6/20/2016

ModelViewController(MVC)InPHPTutorial

2.<head></head>
3.<body>
4.<?php
5.echo'Title:'.$book>title.'<br/>'
6.echo'Author:'.$book>author.'<br/>'
7.echo'Description:'.$book>description.'<br/>'
8.?>
9.</body>
10.</html>
1.<html>
2.<head></head>
3.<body>
4.<table>
5.<tbody><tr><td>Title</td><td>Author</td><td>Description</td></tr></tbody>
6.<?php
7.foreach($booksas$title=>$book)
8.{
9.echo'<tr><td><ahref="index.php?book='.$book>title.'">'.$book>title.'</a></td><td>'.$book
>author.'</td><td>'.$book>description.'</td></tr>'
10.}
11.?>
12.</table>
13.</body>
14.</html>
TheaboveexampleisasimplifiedimplementationinPHP.MostofthePHPwebframeworksbasedonMVC
havesimilarimplementations,inamuchbettershape.However,thepossibilityofMVCpatternareendless.For
exampledifferentlayerscanbeimplementedindifferentlanguagesordistributedondifferentmachines.AJAX
applicationscanimplementstheViewlayerdirectlyinJavascriptinthebrowser,invokingJSONservices.The
controllercanbepartiallyimplementedonclient,partiallyonserver
ThispostshouldnotbeendedbeforeenumeratingtheadvantagesofModelViewControllerpattern:
theModelandViewareseparated,makingtheapplicationmoreflexible.
theModelandviewcanbechangedseparately,orreplaced.Forexampleawebapplicationcanbe
transformedinasmartclientapplicationjustbywritinganewViewmodule,oranapplicationcanuseweb
servicesinthebackendinsteadofadatabase,justreplacingthemodelmodule.
eachmodulecanbetestedanddebuggedseparately.
Thefilesareavailablefordownloadasazipfromhttp://sourceforge.net/projects/mvc
php/files/mvc.zip/download
Didyouenjoythistutorial?BesuretosubscribetotheourRSSfeednottomissournewtutorials!
...ormakeitpopularon

http://phphtml.net/tutorials/modelviewcontrollerinphp/

4/4

Anda mungkin juga menyukai