I want to send mails to users for which Iam creating a model with name 'Common'. Common model has the function 'test' to send mails. But the model is giving error:
Fatal error: Call to undefined method Common::model()
here is my model code:
<?php
class Common extends CFormModel
{
public $from;
public $to;
public function rules()
{
return array(
array('from, to', 'required'),
);
}
public function attributeLabels()
{
return array(
'from' => 'From',
'to' => 'To',
);
}
public function test($id)
{
print_r($id); die("sfbvjzsb");
------------------------------------------
sending mail code
--------------------------------------------
}
}
?>
Iam calling the model in controller as below:
Common::model()->test($group_id);
Where Iam doing wrong?
Well, you don't have a static method named model().
You can do this:
$c = new Common();
$c->test($group_id);
Or , if you change the declaration of the test function to:
public static function test($id)
then you will be able to call it statically like this:
Common::test($group_id);
Related
I have my job class ProductPublish method handle() I am trying to send email.
public function handle()
{
//
Mail::to('i******o#gmail.com')->send(new SendEmail());
}
In the ProductController controller I am calling that job class as like below
ProductPublish::dispatch();
In the SendEmail class which is mailable I am trying to pass data to view as like below
public $message;
public function __construct($message)
{
$this->message = 'This is test message';
}
public function build()
{
return $this->view('email.product.product-publish')->with('message' => $this->message);
}
But it does not works. I also tried with no attaching with() method but still does getting result. In the email view I am calling data as like below
{{ $message }}
Can someone kindly guide me what can be issue that it is not working. Also I want to pass data actually from ProductController but since I am failed to pass from sendEmail that's I didn't tried yet from controller.
Kindly guide me how can I fix it.
In laravel,
The arguments passed to the dispatch method will be given to the job's constructor
So when you are calling dispatch, you can pass message :
ProductPublish::dispatch($message);
Then inside your job you can add a property message and a constructor to get it from dispatch and assign it :
private $message;
public function __construct($message)
{
$this->message = $message;
}
public function handle()
{
// Use the message using $this->messge
Mail::to('i******o#gmail.com')->send(new SendEmail($this->message));
}
Also you can directly queue emails. Check documentation
Try this:
public $message;
public function __construct($message)
{
$this->message= $message;
}
public function build()
{
// Array for passing template
$input = array(
'message' => $this->message
);
return $this->view('email.product.product-publish')
->with([
'inputs' => $input,
]);
}
Check Docs
I am trying to extend an existing plugin component and I
need to add a function but use plugins methods.
Here what I have:
<?php namespace Bbrand\Shop\Components;
use Cms\Classes\ComponentBase;
use Jiri\JKShop\Components\Basket;
class Shopextend extends ComponentBase
{
public function componentDetails()
{
return [
'name' => 'shopextend Component',
'description' => 'No description provided yet...'
];
}
public function defineProperties()
{
return [];
}
public function onBasket(){
$data = [];
$data["basket"] = Basket::getSessionBasket();
$data["jkshopSetting"] = \Jiri\JKShop\Models\Settings::instance();
return [
$this->property("idElementWrapperBasketComponent") => $this->renderPartial('#basket-0', $data)
];
}
}
But I'm getting an error
"Non-static method Jiri\JKShop\Components\Basket::getSessionBasket()
should not be called statically" on line 30 of
/Applications/MAMP/htdocs/fidgycube.co/plugins/bbrand/shop/components/Shopextend.php
Any help!?
thanks
You need to add component first.
<?php namespace Bbrand\Shop\Components;
class Shopextend extends ComponentBase
{
public function init()
{
// Add component
$this->addComponent('\Jiri\JKShop\Components\Basket', 'basket', []);
}
}
I am quite new to ZF2 and I am preparing a demo application with simple login and CRUD system. Now for login I have prepared a plugin which consists of some functions that will authenticate users, return the logged in user data, return the logged in status etc. But the problem that I am facing is I can't initialize any variable into the constructor of my controller which will store any return value from the plugin. It's always showing service not found exception.
Please find my plugin code below:
AuthenticationPlugin.php
<?php
namespace Album\Controller\Plugin;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\Session\Container as SessionContainer;
use Zend\View\Model\ViewModel;
use Album\Entity\User;
class AuthenticationPlugin extends AbstractPlugin{
protected $entityManager;
protected $usersession;
public function __construct(){
$this->usersession = new SessionContainer('UserSession');
}
public function dologin($email,$password)
{
$getData = $this->em()->getRepository('Album\Entity\User')->findOneBy(array('email' => $email, 'password' => $password));
if(count($getData)){
$this->usersession->offsetSet('userid', $getData->getId());
return true;
}
else{
return false;
}
}
public function isloggedin(){
$userid = $this->usersession->offsetGet('userid');
if(!empty($userid)){
return true;
}
else{
return false;
}
}
public function logindata(){
$userid = $this->usersession->offsetGet('userid');
$getData = $this->em()->getRepository('Album\Entity\User')->findOneBy(array('id' => $userid));
return $getData;
}
public function logout(){
$this->usersession->offsetUnset('userid');
}
public function em(){
return $this->entityManager = $this->getController()->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
}
?>
In my module.config.php
'controller_plugins' => array(
'invokables' => array(
'AuthPlugin' => 'Album\Controller\Plugin\AuthenticationPlugin',
)
),
Now I am doing this in my controller:
protected $entityManager;
protected $isloggedin;
protected $authentication;
public function __construct(){
$this->authentication = $this->AuthPlugin();
$this->isloggedin = $this->authentication->isloggedin();
}
The error I am getting is like below:
An error occurred An error occurred during execution; please try again
later. Additional information:
Zend\ServiceManager\Exception\ServiceNotFoundException
File:
D:\xampp\htdocs\subhasis\zf2-tutorial\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php:555
Message:
Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for AuthPlugin
But if I write the above constructor code in any of my controller actions everything is fine. in ZF1 I could initialize any variable in the init() method and could use the variable in any of my actions. How can I do this in ZF2? Here, I want to detect if the user is logged in the constructor itself. Now I have to call the plugin in every action which I don't want.
What should I do here?
The error you are receiving is because you are trying to use the ServiceManager (via the Zend\Mvc\Controller\PluginManager) in the __construct method of the controller.
When a controller is registered as an invokable class, the Service Manager (ControllerManager) is responsible for the creating the controller instance. Once created, it will then call the controllers various default 'initializers' which also inlcudes the plugin manager. By having your code in __construct it is trying to use the plugin manager before it has been set.
You can resolve this by using a controller factory, rather than an invokable in module.config.php.
'controllers' => [
'factories' => [
'MyModule\Controller\Foo' => 'MyModule\Controller\FooControllerFactory',
],
],
Then the factory
namespace MyModule\Controller\FooControllerFactory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class FooControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $controllerManager)
{
$serviceManager = $controllerManager->getServiceLocator();
$controllerPluginManager = $serviceManager->get('ControllerPluginManager');
$authPlugin = $controllerPluginManager->get('AuthPlugin');
return new FooController($authPlugin);
}
}
Lastly, update the controller __construct to add the new argument and remove the call to $this->authPlugin()
class FooController extends AbstractActionController
{
public function __construct(AuthPlugin $authentication)
{
$this->authentication = $authentication;
$this->isloggedin = $authentication->isloggedin();
}
}
I'm attempting to write a test for a model that has no table but sends an email if the data passes validation in CakePHP 2.
To test I want to assert that some data passes validation and would therefore send an email without actually sending one. For this I am attempting to create a mock method for CakeEmail. However, the test is failing because $useDbConfig hasn't be defined for the mock method:-
Undefined property: Mock_MyModel_7a1fb8d0::$useDbConfig
I assume this is an issue with the model not having a table, but cannot see how to resolve it.
My model looks something like (excluding the validation rules):-
<?php
App::uses('CakeEmail', 'Network/Email');
class MyModel extends AppModel {
public $useTable = false;
public function send($data) {
$this->set($data);
if ($this->validates() === false) {
return false;
} else {
$Email = $this->getEmailer();
$Email->from($data['MyModel']['email_from']);
$Email->to($data['MyModel']['email_to']);
$Email->subject($data['MyModel']['subject']);
$Email->send($data['MyModel']['message']);
}
return true;
}
public function getEmailer() {
return new CakeEmail();
}
}
My test is:-
<?php
class MyModel extends CakeTestCase {
public function setUp() {
parent::setUp();
$this->MyModel = ClassRegistry::init('MyModel');
}
public function testSend() {
$emailer = $this->getMock(
'CakeEmail',
array(
'to',
'emailFormat',
'subject',
'replyTo',
'from',
'template',
'viewVars',
'send'
)
);
$emailer->expects($this->any())->method('send')->will($this->returnValue(true));
$MyModel = $this->getMockForModel('MyModel', array('getEmailer'));
$MyModel->expects($this->once())->method('getEmailer')->will($this->returnValue($emailer));
$data = array(
'MyModel' => array(
'email_to' => 'foo#example.com',
'email_from' => 'bar#example.com',
'subject' => 'Foo bar',
'message' => ''
)
);
$result = $MyModel->send($data);
$this->assertTrue($result);
}
}
Any help would be appreciated. This is the first time I've tried/needed to mock a method in Cake using tests.
Class name should have been MyModelTest rather than MyModel. CakePHP's naming convention needs to be adhered to.
I'm overriding the create() Eloquent method, but when I try to call it I get Cannot make static method Illuminate\\Database\\Eloquent\\Model::create() non static in class MyModel.
I call the create() method like this:
$f = new MyModel();
$f->create([
'post_type_id' => 1,
'to_user_id' => Input::get('toUser'),
'from_user_id' => 10,
'message' => Input::get('message')
]);
And in the MyModel class I have this:
public function create($data) {
if (!Namespace\Auth::isAuthed())
throw new Exception("You can not create a post as a guest.");
parent::create($data);
}
Why doesn't this work? What should I change to make it work?
As the error says: The method Illuminate\Database\Eloquent\Model::create() is static and cannot be overridden as non-static.
So implement it as
class MyModel extends Model
{
public static function create($data)
{
// ....
}
}
and call it by MyModel::create([...]);
You may also rethink if the auth-check-logic is really part of the Model or better moving it to the Controller or Routing part.
UPDATE
This approach does not work from version 5.4.* onwards, instead follow this answer.
public static function create(array $attributes = [])
{
$model = static::query()->create($attributes);
// ...
return $model;
}
Probably because you are overriding it and in the parent class it is defined as static.
Try adding the word static in your function definition:
public static function create($data)
{
if (!Namespace\Auth::isAuthed())
throw new Exception("You can not create a post as a guest.");
return parent::create($data);
}
Of course you will also need to invoke it in a static manner:
$f = MyModel::create([
'post_type_id' => 1,
'to_user_id' => Input::get('toUser'),
'from_user_id' => 10,
'message' => Input::get('message')
]);