Reputation: 20178
I have a method in a controller say like this. In fact, I'm in need to declare a function checkLogin so that I can use in several Controller method like below:
class DefaultController extends Controller
{
/**
* @Route("/test")
* @Template()
*/
public function testAction()
{
if (checkLogin()){}
else {}
exit;
}
public static function checkLogin()
{
return 1;
}
}
In the above case, when I'm doing it like this, I'm getting the following error:
Fatal error: Call to undefined function NouPei\WebSiteBundle\Controller\checkLogin() in /home/noor/noupei/website/WebSiteBundle/Controller/DefaultController.php on line 142
Upvotes: 9
Views: 28796
Reputation: 692
There are several ways to do this:
Use the firewall provided by Symfony. You can configure it in app/config/security.yml under the access_control: - { path: ^/anyurl-form/pattern$, role: ROLE_USER }
using this method: symfony will be the one to verify the validity of the session. and if the session is invalid, it will redirect the user automatically to login page and an unauthenticated user will never be able to visit these pages if not loggedin.
Implementing this method has several options too before it will work. You might need to create your own Provider or Use and existing one I recommend FOSUserBundle. This bundle has a variety on how to manage the user. Another option is creating your own Provider if you want to validate externally specially when you are using api's (SOA) to check the authenticity of the user.
If you want to add a method that will be used for all Controller. It's either you create a Class that extends Symfony's Controller:
class BaseController extends Controller { protected function checkLogin(){} }
class DefaultController extends BaseController { public function testAction() { $loggedIn = $this->checkLogin(); } }
Or you can create a trait and include it in your Controller.
trait ControllerTrait
{
protected function checkLogin(){}
}
class DefaultController extends BaseController
{
use ControllerTrait;
public function testAction()
{
$loggedIn = $this->checkLogin();
}
}
But I highly recommend using the firewall for security purposes and it offers a lot of functionality and security checking.
Upvotes: 2
Reputation: 649
For account management in Symfony 2, you should use the security management of symfony 2 (here). You will be able to check user login like this :
public function indexAction()
{
// show different content to admin users
if ($this->get('security.context')->isGranted('ADMIN')) {
// Load admin content here
}
// load other regular content here
}
If you don't want to use Symfony 2 security management, you should use services to make methods available for every controllers.
Upvotes: 5