控制器ControllerSymfonyWord下载.docx
- 文档编号:21426223
- 上传时间:2023-01-30
- 格式:DOCX
- 页数:15
- 大小:22.37KB
控制器ControllerSymfonyWord下载.docx
《控制器ControllerSymfonyWord下载.docx》由会员分享,可在线阅读,更多相关《控制器ControllerSymfonyWord下载.docx(15页珍藏版)》请在冰豆网上搜索。
Hereareafewcommonexamples:
ControllerApreparesaResponseobjectrepresentingthecontentforthehomepageofthesite.
ControllerBreadstheslugparameterfromtherequesttoloadablogentryfromthedatabaseandcreateaResponseobjectdisplayingthatblog.Iftheslugcan’tbefoundinthedatabase,itcreatesandreturnsaResponseobjectwitha404statuscode.
ControllerChandlestheformsubmissionofacontactform.Itreadstheforminformationfromtherequest,savesthecontactinformationtothedatabaseandemailsthecontactinformationtoyou.Finally,itcreatesaResponseobjectthatredirectstheclient’sbrowsertothecontactform“thankyou”page.
Requests->
Controller->
Response的过程
EveryrequesthandledbyaSymfonyprojectgoesthroughthesamesimplelifecycle.Theframeworktakescareofalltherepetitivestuff:
youjustneedtowriteyourcustomcodeinthecontrollerfunction:
Eachrequestishandledbyasinglefrontcontrollerfile(e.g.app.phporapp_dev.php)thatbootstrapstheapplication;
TheRouterreadsinformationfromtherequest(e.g.theURI),findsaroutethatmatchesthatinformation,andreadsthe_controllerparameterfromtheroute;
ThecontrollerfromthematchedrouteisexecutedandthecodeinsidethecontrollercreatesandreturnsaResponseobject;
TheHTTPheadersandcontentoftheResponseobjectaresentbacktotheclient.
Creatingapageisaseasyascreatingacontroller(#3)andmakingaroutethatmapsaURLtothatcontroller(#2).
注解
Thoughsimilarlynamed,a“frontcontroller”isdifferentfromthe“controllers”talkedaboutinthischapter.AfrontcontrollerisashortPHPfilethatlivesinyourwebdirectoryandthroughwhichallrequestsaredirected.Atypicalapplicationwillhaveaproductionfrontcontroller(e.g.app.php)andadevelopmentfrontcontroller(e.g.app_dev.php).You’lllikelyneverneedtoedit,vieworworryaboutthefrontcontrollersinyourapplication.
简单示例
WhileacontrollercanbeanyPHPcallable(afunction,methodonanobject,oraClosure),acontrollerisusuallyamethodinsideacontrollerclass.Controllersarealsocalledactions.
//src/AppBundle/Controller/HelloController.php
namespaceAppBundle\Controller;
classHelloController
publicfunctionindexAction($name)
{
<
html>
body>
Hello'
.$name.'
!
/body>
/html>
}
小技巧
NotethatthecontrolleristheindexActionmethod,whichlivesinsideacontrollerclass(HelloController).Don’tbeconfusedbythenaming:
acontrollerclassissimplyaconvenientwaytogroupseveralcontrollers/actionstogether.Typically,thecontrollerclasswillhouseseveralcontrollers/actions(e.g.updateAction,deleteAction,etc).
Thiscontrollerisprettystraightforward:
line4:
SymfonytakesadvantageofPHP’snamespacefunctionalitytonamespacetheentirecontrollerclass.TheusekeywordimportstheResponseclass,whichthecontrollermustreturn.
line6:
Theclassnameistheconcatenationofanameforthecontrollerclass(i.e.Hello)andthewordController.Thisisaconventionthatprovidesconsistencytocontrollersandallowsthemtobereferencedonlybythefirstpartofthename(i.e.Hello)intheroutingconfiguration.
line8:
EachactioninacontrollerclassissuffixedwithActionandisreferencedintheroutingconfigurationbytheaction’sname(index).Inthenextsection,you’llcreatearoutethatmapsaURItothisaction.You’lllearnhowtheroute’splaceholders({name})becomeargumentstotheactionmethod($name).
line10:
ThecontrollercreatesandreturnsaResponseobject.
创建URL->
Controller的映射关系
ThenewcontrollerreturnsasimpleHTMLpage.Toactuallyviewthispageinyourbrowser,youneedtocreatearoute,whichmapsaspecificURLpathtothecontroller:
Annotations
useSensio\Bundle\FrameworkExtraBundle\Configuration\Route;
/**
*@Route("
/hello/{name}"
name="
hello"
)
*/
YAML
#app/config/routing.yml
hello:
path:
/hello/{name}
#usesaspecialsyntaxtopointtothecontroller-seenotebelow
defaults:
{_controller:
AppBundle:
Hello:
index}
XML
--app/config/routing.xml-->
?
xmlversion="
1.0"
encoding="
UTF-8"
?
>
routesxmlns="
xmlns:
xsi="
http:
//www.w3.org/2001/XMLSchema-instance"
xsi:
schemaLocation="
<
routeid="
path="
--usesaspecialsyntaxtopointtothecontroller-seenotebelow-->
defaultkey="
_controller"
AppBundle:
index<
/default>
/route>
/routes>
PHP
//app/config/routing.php
useSymfony\Component\Routing\Route;
useSymfony\Component\Routing\RouteCollection;
$collection=newRouteCollection();
$collection->
add('
hello'
newRoute('
/hello/{name}'
array(
//usesaspecialsyntaxtopointtothecontroller-seenotebelow
'
_controller'
=>
index'
)));
return$collection;
Now,youcangoto/hello/ryan(e.g.http:
//localhost:
8000/app_dev.php/hello/ryanifyou’reusingthebuilt-inwebserver)andSymfonywillexecutetheHelloController:
indexAction()controllerandpassinryanforthe$namevariable.Creatinga“page”meanssimplycreatingacontrollermethodandanassociatedroute.
Simple,right?
TheAppBundle:
indexcontrollersyntax
IfyouusetheYMLorXMLformats,you’llrefertothecontrollerusingaspecialshortcutsyntax:
index.Formoredetailsonthecontrollerformat,seeController命名规则.
参见
YoucanlearnmuchmoreabouttheroutingsystemintheRoutingchapter.
使用Route参数作为Controller参数
YoualreadyknowthattheroutepointstotheHelloController:
indexAction()methodthatlivesinsideAppBundle.What’smoreinterestingistheargumentthatispassedtothatmethod:
//...
/**
publicfunctionindexAction($name)
//...
Thecontrollerhasasingleargument,$name,whichcorrespondstothe{name}parameterfromthematchedroute(ryanifyougoto/hello/ryan).Whenexecutingyourcontroller,Symfonymatcheseachargumentwithaparameterfromtheroute.Sothevaluefor{name}ispassedto$name.
Takethefollowingmore-interestingexample:
/hello/{firstName}/{lastName}"
publicfunctionindexAction($firstName,$lastName)
/hello/{firstName}/{lastName}
/
//www.baiyuewang.ne/schema/routing
/hello/{firstName}/{lastName}'
Now,thecontrollercanhavetwoarguments:
publicfunctionindexAction($firstName,$lastName)
Mappingrouteparameterstocontrollerargumentsiseasyandflexible.Keepthefollowingguidelinesinmindwhileyoudevelop.
Theorderofthecontrollerargumentsdoesnotmatter
Symfonymatchestheparameternamesfromtheroutetothevariablenamesofthecontroller.Theargumentsofthecontrollercouldbetotallyreorderedandstillworkperfectly:
publicfunctionindexAction($lastName,$firstName)
Eachrequiredcontrollerargumentmustmatchupwitharoutingparameter
ThefollowingwouldthrowaRuntimeExceptionbecausethereisnofooparameterdefinedintheroute:
publicfunctionindexAction($firstName,$lastName,$foo)
Makingtheargumentoptional,however,isperfectlyok.Thefollowingexamplewouldnotthrowanexception:
publicfunctionindexAction($firstNam
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 控制器 ControllerSymfony
![提示](https://static.bdocx.com/images/bang_tan.gif)