Way one
$name =new Text( 'name', [....] );
$name->setLabel( ..... );
$name->setDefault( .... );
$form->add( $name );
Way two. Note the mising ; at the end of the second line except the last. This why you can chain your calls. You can place the chained commands below or on one line. Whatever you find more appealing to you.
$name =new Text( 'name', [....] );
$name->setLabel( ..... )
->setDefault( .... );
$name->setLabel( ... )->setDefault( ... );
$form->add( $name );
Way three. Note the extra () around the new call. This means that this is executed first and after that setLabel and setDefault are called
$form->add(( new Text( 'name', [....] ))
->setLabel( ..... )
->setDefault( .... )
);
Here an example that I use myself. It is a small form that I use to manage menu's in my application. I used the first way myself when I started with phalcon, but I have switched to the way below. I find it easier to read and also makes things a little compacter.
<?php
namespace Modules\menus\Forms;
use Backend\Common\BaseForm;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Hidden;
use Phalcon\Validation\Validator\PresenceOf;
class MenuForm extends BaseForm
{
public function initialize( $entity=null, $options=null )
{
parent::initialize( $entity, $options );
// Id
$this->add(( new Hidden( 'id' )));
// Name
$this->add(
( new Text( 'name' ))
->setLabel( 'Name' )
->addValidators([
new PresenceOf([ 'message' => 'Name is required' ]),
])
);
// Label
$this->add(
( new Text( 'label' ))
->setLabel( 'Label' )
->addValidators([
new PresenceOf([ 'message' => 'Label is required' ]),
])
);
}
}
As for how you should structure your code is up to you. You can make up your own structure that you are comfortable with or you could adhere to PSR standards out there. Experiment with them if you like to get an idea what suits you the best.