Q:

Symfony2 code organization: where should logic for encrypting password before persisting to db go?

If you use a database to store users you could save user info as shown below:
(from the Symfony security book.)
$factory = $this->get('security.encoder_factory');
$user = new Acme\UserBundle\Entity\User();

$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword('mypassword', $user->getSalt());
$user->setPassword($password);

However, I want to create reusable a User form:
namespace App\Bundle\WebBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class UserType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('username')
            ->add('password')
        ;
    }

    public function getName()
    {
        return 'app_bundle_webbundle_usertype';
    }
}

And use the form in a controller:
(from here)
if ($request->getMethod() == 'POST') {
    $form->bindRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($task);
        $em->flush();

        return $this->redirect($this->generateUrl('task_success'));
    }
}

Where should you put the code used to hash your password shown at the beginning of this post (and the code to generate the salt, for that matter) in order to make it reusable and compatible with the $form->bindRequest() approach, in case you need for both a user registration form and a user profile edit form, etc?

A:

I recommend looking into: https://github.com/FriendsOfSymfony/FOSUserBundle . Even if you want to write your own solution, you can get very good ideas from that bundle.

