Start Symfony
创建一个路由匹配
# app/config/routing.yml
lucky_number:
path: /lucky/number/{count}
defaults: { _controller: AppBundle:Lucky:number }
然后在对应的路由编写对应的代码
// src/AppBundle/Controller/LuckyController.php
// ...
class LuckyController
{
public function numberAction($count)
{
$numbers = array();
for ($i = 0; $i < $count; $i++) {
$numbers[] = rand(0, 100);
}
$numbersList = implode(', ', $numbers);
return new Response(
'<html><body>Lucky numbers: '.$numbersList.'</body></html>'
);
}
// ...
}
去/lucky/number/xx
测试一下,把xx
换为任意数字:
http://localhost:8000/api/lucky/number/7
渲染模板(利用容器)
// src/AppBundle/Controller/LuckyController.php
// ...
// --> add this new use statement
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class LuckyController extends Controller
{
public function numberAction($count)
{
// ...
/*
$html = $this->container->get('templating')->render(
'lucky/number.html.twig',
array('luckyNumberList' => $numbersList)
);
return new Response($html);
*/
// render: a shortcut that does the same as above 快捷方法
return $this->render(
'lucky/number.html.twig',
array('luckyNumberList' => $numbersList)
);
}
}