5. Namespaces
$worker = new Artisan_SomeModule_Foo_Bar();
// vs
use ArtisanSomeModuleFooBar;
// ...
$bar = new Bar();
6. Invoke
class Slug {
private $regexp;
public function __construct($regexp) {
$this->regexp = $regexp;
}
public function __invoke($value) {
return strtolower(preg_replace($this->regexp, "-", $value));
}
}
$filter = new Slug("#^[^A-Z0-9]$#i");
echo $filter("Hello World"); // outputs hello-world
7. Late Static Binding
abstract class Singleton
{
protected static $instance;
protected function __construct() { }
final public static function getInstance() {
if (null === static::$instance) {
static::$instance = new static();
}
return static::$instance;
}
final private function __clone() { }
}
23. Twig
namespace ArtisanFooBundleTwigExtension;
class TextExtension extends Twig_Extension
{
public function getFilters()
{
return array(
'upper' => new Twig_Filter_Method($this, 'upper'),
);
}
public function upper($value)
{
return strtoupper($value);
}
public function getName()
{
return 'text';
}
}
25. Standard Classes
class Widget
{
protected $id;
protected $name;
}
26. Give Me My
Constructor Back
class Widget
{
protected $id;
protected $name;
public function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
}
38. Validation
namespace ArtisanWidgetBundleController;
use SymfonyBundleFrameworkBundleControllerController;
class WidgetController extends Controller
{
public function indexAction($name)
{
$widget = new Widget();
// do something with the widget...
$errors = $this->get("validator")->validate($widget);
return $this->render('HelloBundle:hello:index.html.twig', array(
"errors" => $errors
));
}
}
43. Forms
public function newAction()
{
$widget = new Widget();
$form = $this->createFormBuilder($widget)
->add('name', 'text')
->getForm();
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
// do something to save widget...
return $this->redirect($this->generateUrl('widget_success'));
}
}
return $this->render('WidgetBundle:widget:new.html.twig', array(
"errors" => $errors
));
}