I have a file in app/Console/Commands/SendEmail.php with this content:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SendEmail extends Command
{
protected $signature = 'send_email';
protected $description = 'Command description';
public function __construct()
{
parent::__construct();
}
public function handle()
{
echo "hello wordl\n";
}
}
I added these lines into routes/console.php:
use App\Console\Commands\SendEmail;
Artisan::command('send_email', function() { });
And the question is: what I need to write into the routes/console.php file to run this command?
Related
I am beginning coding in codeigniter, here after the submit button the data should be insert on database and redirect to next page. For me inserting on database is successfully done but the page is not redirecting;
this is my controller - Home.php
but i am getting error as The requested URL /code/display was not found on this server.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('demo');
//$this->load->model('Insert_data');
}
public function savedata()
{
if($this->input->post('submit'))
{
$data=array(
'name'=>$this->input->post('name'),
'email'=>$this->input->post('email'),
'content'=>$this->input->post('content'));
$result=$this->Insert_data->saverecords($data);
if ($result)
{
echo "Records Saved Successfully";
redirect(base_url().'Home/display');
}
else
{
echo "Records not Saved Successfully";
}
}
}
public function display()
{
$this->load->view('display');
}
}
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('demo');
//$this->load->model('Insert_data');
}
public function savedata()
{
if($this->input->post('submit'))
{
$data=array(
'name'=>$this->input->post('name'),
'email'=>$this->input->post('email'),
'content'=>$this->input->post('content'));
$result=$this->Insert_data->saverecords($data);
if ($result==1)
{
echo "Records Saved Successfully";
redirect('Home/display');
}
else
{
echo "Records not Saved Successfully";
}
}
}
public function display()
{
$this->load->view('display');
}
}
I am trying to change 'myemail#gmail.com' address to something like: no-reply#gmail.com and trying to add a custom address but I am unable to get it to work.
Which file do I add the subject and from?
my .env file
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=myemail#gmail.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=no-reply#example.com
MAIL_FROM_NAME="Custom App Name"
controller code
dispatch(new JblockedUser($user));
jobs file
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Mail;
use App\User;
use Carbon\Carbon;
use App\Mail\BlockedUser;
class JblockedUser implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $user;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$email = new BlockedUser($this->user);
Mail::to('example#gmail.com')->queue($email);
}
}
mail file
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class BlockedUser extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->markdown('emails.newsletter');
}
}
You can set the from and subject in your mailable build method. By default if no from address is provided, then laravel uses the global from address and name set in the config file. The default subject will be built using your mailable class name. In your case Blocked User would be the subject.
public function build()
{
return $this->from('no-reply#example.com')
->subject('Newsletter!!!')
->markdown('emails.newsletter');
}
Or if you need to specify the email and name.
public function build()
{
$from = [
'address' => 'no-reply#example.com',
'name' => 'Custom App Name'
];
return $this->from($from)
->subject('Newsletter!!!')
->markdown('emails.newsletter');
}
You might want to run php artisan config:clear in case your .env file changes aren't reflecting.
I want to redirect the user to another form just after registration, before he could access to anything on my website (like in https://github.com/FriendsOfSymfony/FOSUserBundle/issues/387).
So I create an eventListener like in the doc :
<?php
namespace rs\UserBundle\EventListener;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\UserEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Listener responsible to change the redirection at the end of the password resetting
*/
class RegistrationConfirmedListener implements EventSubscriberInterface
{
private $router;
public function __construct(UrlGeneratorInterface $router)
{
$this->router = $router;
}
/**
* {#inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_CONFIRMED => 'onRegistrationConfirmed'
);
}
public function onRegistrationConfirmed()
{
$url = $this->router->generate('rsWelcomeBundle_check_full_register');
$response = new RedirectResponse($url);
return $response;
}
}
Services.yml :
services:
rs_user.registration_completed:
class: rs\UserBundle\EventListener\RegistrationConfirmedListener
arguments: [#router]
tags:
- { name: kernel.event_subscriber }
But it doesn't work, the user register, he click on the confirmation link in his mailbox, he is not redirected on the page I want, he is logged and I just have the message who said the account is confirmed.
Why it doesn't redirect me to the route : rsWelcomeBundle_check_full_register like I want ?
Thanks
To accomplish what you want, you should use FOSUserEvents::REGISTRATION_CONFIRM instead of FOSUserEvents::REGISTRATION_CONFIRMED.
You then have to rewrite rewrite your class RegistrationConfirmedListener like:
class RegistrationConfirmListener implements EventSubscriberInterface
{
private $router;
public function __construct(UrlGeneratorInterface $router)
{
$this->router = $router;
}
/**
* {#inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_CONFIRM => 'onRegistrationConfirm'
);
}
public function onRegistrationConfirm(GetResponseUserEvent $event)
{
$url = $this->router->generate('rsWelcomeBundle_check_full_register');
$event->setResponse(new RedirectResponse($url));
}
}
And your service.yml:
services:
rs_user.registration_complet:
class: rs\UserBundle\EventListener\RegistrationConfirmListener
arguments: [#router]
tags:
- { name: kernel.event_subscriber }
REGISTRATION_CONFIRM receives a FOS\UserBundle\Event\GetResponseUserEvent instance as you can see here: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/FOSUserEvents.php
It allows you to modify the response that will be sent: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Event/GetResponseUserEvent.php
"friendsofsymfony/user-bundle": "2.0.x-dev",
Not sure why the accepted answer works for you as REGISTRATION_CONFIRM happens after the token is confirmed.
In case you want to perform an action, redirect to another page with some additional form after the FOS registerAction I would suggest the following way.
This is the code that is performed on registerAction once the submitted form is valid by FOS:
FOS\UserBundle\Controller\RegistrationController
if ($form->isValid()) {
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
As you can see the first possible return happens after FOSUserEvents::REGISTRATION_SUCCESS event in case the response is null which in my case doesn't as I have configured a mailer to send a confirmation token and FOS is using an listener that listens to this FOSUserEvents::REGISTRATION_SUCCESS event and after sending an email it sets a redirect response.
FOS\UserBundle\EventListener\EmailConfirmationListener
/**
* #return array
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess',
);
}
/**
* #param FormEvent $event
*/
public function onRegistrationSuccess(FormEvent $event)
{
/** #var $user \FOS\UserBundle\Model\UserInterface */
$user = $event->getForm()->getData();
$user->setEnabled(false);
if (null === $user->getConfirmationToken()) {
$user->setConfirmationToken($this->tokenGenerator->generateToken());
}
$this->mailer->sendConfirmationEmailMessage($user);
$this->session->set('fos_user_send_confirmation_email/email', $user->getEmail());
$url = $this->router->generate('fos_user_registration_check_email');
$event->setResponse(new RedirectResponse($url));
}
Okay I understand! So how do I redirect to another page?
I would suggest to overwrite checkEmailAction as most likely you don't want to overwrite the listener that sends an email as that's part of your workflow.
Simply:
TB\UserBundle\Controller\RegistrationController
/**
* #return \Symfony\Component\HttpFoundation\Response
*/
public function checkEmailAction()
{
/** #var UserManager $userManager */
$userManager = $this->get('fos_user.user_manager');
/** #var string $email */
$email = $this->get('session')->get('fos_user_send_confirmation_email/email');
$user = $userManager->findUserByEmail($email);
return $this->redirect($this->generateUrl('wall', ['username' => $user->getUsername()]));
}
As you can see instead of rendering FOS's check_email template I decided to redirect user to his new profile.
Docs how to overwrite an controller: https://symfony.com/doc/master/bundles/FOSUserBundle/overriding_controllers.html (basically define a parent for your bundle and create a file in the directory with the same name as FOS does.)
Route redirection can also be used:
fos_user_registration_confirmed:
path: /register/confirmed
defaults:
_controller: FrameworkBundle:Redirect:redirect
route: redirection_route
permanent: true
If you're not using a confirmation email, you can redirect the user right after submiting the registration form this way :
class RegistrationConfirmationSubscriber implements EventSubscriberInterface
{
/** #var Router */
private $router;
public function __construct(Router $router)
{
$this->router = $router;
}
public static function getSubscribedEvents()
{
return [FOSUserEvents::REGISTRATION_COMPLETED => 'onRegistrationConfirm'];
}
public function onRegistrationConfirm(FilterUserResponseEvent $event)
{
/** #var RedirectResponse $response */
$response = $event->getResponse();
$response->setTargetUrl($this->router->generate('home_route'));
}
}
The subscriber declaration stay the same :
registration_confirmation_subscriber:
class: AppBundle\Subscriber\RegistrationConfirmationSubscriber
arguments:
- "#router"
tags:
- { name: kernel.event_subscriber }
For a quick solution: you can also override the route. Let's say you want to redirect to your homepage you can do something like this:
/**
* #Route("/", name="index")
* #Route("/", name="fos_user_registration_confirmed")
* #Template(":Default:index.html.twig")
*/
public function indexAction()
{
I'm trying to create unit test with phpunit for Zend, using Doctrine ORM. When I try to create a test class extending Zend_Test_PHPUnit_DatabaseTestCase, I get a message when executing PHPUnit: "There is no open connection"
Here is the full source:
<?php
class AclTest extends Zend_Test_PHPUnit_DatabaseTestCase
{
private $_userAdmin;
public function setUp()
{
$this->bootstrap = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
$this->_userAdmin = Model_UserTable::getInstance()->findOneByUsername('admin');
parent::setUp();
}
protected function getConnection()
{
$pdo = new PDO('mysql:host=localhost;dbname=mydbname', 'root', 'pwd');
return $this->createDefaultDBConnection($pdo, 'testdb');
}
protected function getDataSet()
{
return null;
}
public function testHasProfilPermission()
{
//execute some tests
}
}
What do you think ?
Thanks
Try this, please:
class AclTest extends Zend_Test_PHPUnit_DatabaseTestCase
{
private $_userAdmin;
/** #var PDO **/
protected $pdo;
public function __construct()
{
$this->pdo = new PDO('mysql:host=localhost;dbname=mydbname', 'root', 'pwd');
}
public function setUp()
{
$this->bootstrap = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
$this->_userAdmin = Model_UserTable::getInstance()->findOneByUsername('admin');
parent::setUp();
}
protected function getConnection()
{
return $this->createDefaultDBConnection($this->pdo, 'testdb');
}
}
i am using zend framework 1.10 with doctrine 2. i wonder if in my (doctrine) model class, isit a good idea to reference a variable set by my application (bootstrap.php, variable stored in Zend_Registry, i think its something like a global variable)
what i want to access is the doctrine entityManager. also i want the id of the logged in user
I am building a project with similar setup (ZF 1.10 + Doctrine2) and I've used dependency injection to deal with this situation, much like takeshin said. Here goes full project repository URL: https://bitbucket.org/phpfour/zf-doctrine2. Below are some code excerpts.
Here's my controller:
<?php
require_once APPLICATION_PATH . "/models/PostManager.php";
class IndexController extends Zend_Controller_Action
{
private $_em;
public function init()
{
$this->_em = $this->getInvokeArg('bootstrap')->getResource('doctrine');
}
public function indexAction()
{
$pm = new PostManager($this->_em);
$this->view->posts = $pm->getPublicPosts();
}
My entity manager (or service class):
<?php
class PostManager
{
protected $_em;
public function __construct(Doctrine\ORM\EntityManager $em)
{
$this->_em = $em;
}
public function getPublicPosts()
{
$query = $this->_em->createQuery('SELECT p FROM Entities\Post p WHERE p.visible = true');
$posts = $query->getResult();
return $posts;
}
Hope this helps!
you should simply use Zend_Auth for the logged-in-userId problem, then could do something like the following in your model
class Model extends BaseModel
{
public function something()
{
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$loggedInUserId = $auth->getIdentity()->id;
}
}
}
There is nothing wrong with this approach (unless you are referring to singletons). Use dependency injection where possible.
However I'd create a service (or two) for this.
class Modulename_Services_Servicename
{
public function getCurrentUser() { ... }
public function getCurrentUserModel() { ... }
public function isLogged() { ... }
public function authenticate() { ... }
public function getSomeData()
{
$user = $this->getCurrentUser()
$model = new YourModel($user);
$query = ....;
$result = $query->execute();
return $result;
}
public function getSomeMoreData($usermodel) { ... }
}