Pass values to external class from controller in codeigniter - php

I have a project in codeigniter in which I have to integrate a payment gateway. The payment gateway integration code file is a separate php file. I want to pass some values to the file.
The file looks like the below code(with lots of functions-I reduces to post here)
class NetworkonlieBitmapPaymentIntegration
{
$networkOnlineArray = array('Network_Online_setting' => array(
'MKEY' => "GgjhJHh467HGGjjj",
'MID' => '123456789',
'amount' => '1000',
'name' => 'ADCB',
'currency' => 'PHP',
));
}
$networkOnlineObject = new NetworkonlieBitmapPaymentIntegration($networkOnlineArray);
I tried to make it as a library and as well as another controller but no luck.
how can I pass values to this file

It is better to create a seperate common functions helper inside helper folder.
commonfunctionshelper.php
<?php
function paymentFun($mkey,$mid,$amount,$name,$currency)
{
$networkOnlineArray = array('Network_Online_setting' => array(
'MKEY' => $mkey,
'MID' => $mid,
'amount' => $amount,
'name' => $name,
'currency' => $currency,
));
}
$networkOnlineObject = new NetworkonlieBitmapPaymentIntegration($networkOnlineArray);
}
?>
Now in your Controller load helpers inside your consturctor
ExampleController.php
<?php
class User_controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('commonfunctions_helper');
}
public function check()
{
//calling common functions helper
paymentFun($mkey,$mid,$amount,$name,$currency);
}
}
This is how you can achieve it.

Related

Reusable action Yii2, failed load form view

I want to create a reusable action inside a controller.
Yii2 usually creates the following views:
update -> render form
create -> render form
The problem is, I failed to load this form.
Yii2 throw an error Call to a member function isAttributeRequired() on string
Here is the list of My apps directory.
modules
finance
actions
- BuatPengeluaranDiBukuBankAction.php
controllers
- BukuBankController.php
views
- buku-bank
* create-pengeluaran-by-kasbon.php
* _form-pengeluaran-by-kasbon
I will describe the following code.
BuatPengeluaranDiBukuBankAction.php
class BuatPengeluaranDiBukuBankAction extends Action {
public $modelClass;
public $modelsDetailClass;
public function run() {
$request = Yii::$app->request;
if($this->modelClass->load($request->post)){
... save here & redirect
}
### Calling view
return $this->controller->render('create-pengeluaran-by-kasbon', [
'model' => $this->modelClass,
'modelsDetail' => empty($this->modelsDetailClass) ? [new BukuBankDetail()] : $this->modelsDetailClass,
]);
}
}
BukuBankController.php
class BukuBankController extends Controller {
public function actions() {
return ArrayHelper::merge(parent::actions(),[
'create-pengeluaran-by-kasbon' => [
'class' => BuatPengeluaranDiBukuBankAction::class,
'modelClass' => BukuBank::class,
'modelsDetailClass' => BukuBankDetail::class
]
]);
}
}
create-pengeluaran-by-kasbon.php
<div class="buku-bank-create-by-kasbon">
<?php echo $this->render('_form-pengeluaran-by-kasbon', [ # Failed to load
'model' => $model,
'modelsDetail' => $modelsDetail,
]) ?>
</div>
_form-pengeluaran-by-kasbon
<?php $form = ActiveForm::begin([
'id' => 'dynamic-form',
/*'type' => ActiveForm::TYPE_HORIZONTAL,
'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]*/
]); ?>
.... lot of field here
<?php ActiveForm::end(); ?>
What is happening
'modelClass' => BukuBank::class,
'modelsDetailClass' => BukuBankDetail::class
are passed as strings and not objects to your action class so before use you need to instantiate (create) this models (objects) see code below with comments.
class BuatPengeluaranDiBukuBankAction extends Action {
public $modelClass;
public $modelsDetailClass;
public function run() {
$request = Yii::$app->request;
// create instances of models here
$model = Yii::createObject($this->modelClass);
$modelsDetails = Yii::createObject($this->modelsDetailClass);
// now you can use models
if($model->load($request->post)){
... save here & redirect
}
### Calling view
return $this->controller->render('create-pengeluaran-by-kasbon', [
'model' => $model,
'modelsDetail' => $modelsDetails,
]);
}
}

Access form request from Observer laravel

I am trying to cleanup my controller. I have a lot form fields so I want to use observer to insert for the other model that have relationship with the main model
I have already successfully insert the request to the database in a controller but it seems to long and heavy. See code below
function insert(Request $request){
$bankStatementName = time().'.'.request()->bankStatement->getClientOriginalExtension();
request()->bankStatement->move(public_path('bankStatement'), $bankStatementName);
$identityName = time().'.'.request()->identity->getClientOriginalExtension();
request()->identity->move(public_path('identity'), $identityName);
$passportName = time().'.'.request()->passport->getClientOriginalExtension();
request()->passport->move(public_path('passport'), $passportName);
$customer = Customer::find(Auth::user()->id);
$relations = new Customer_relationship([
'kinName' => $request->kinName,
'kinGender' => $request->kinGender,
'kinEmail' => $request->kinEmail,
'kinRelation' => $request->kinRelation,
'kinAddress' => $request->kinAddress
]);
$company = new Customer_company([
'compName' => $request->compName,
'compEmail' => $request->compEmail,
'compPhone' => $request->compPhone,
'compAddress' => $request->compAddress
]);
$bank = new Customer_bank([
'accNumber' => $request->accNumber,
'bankName' => $request->bankName,
'accName' => $request->accName
]);
$document = new Customer_document([
'identity' => $identityName,
'bankStatement' => $bankStatementName,
'passport' => $passportName
]);
$customer->relation()->save($relations);
$customer->company()->save($company);
$customer->bank()->save($bank);
$customer->document()->save($document);
Customer::where('user_id', Auth::user()->id)
->update([
'title' => $request->title,
'middlename' => isset($request->middlename) ? $request->middlename : "",
'phone' => $request->phone,
'gender' => $request->gender,
'DOB' => $request->DOB,
'marital' => $request->marital,
'residential_address' => $request->residential_address,
'city' => $request->city,
'state' => $request->state,
'lga' => $request->lga,
'nationality' => $request->nationality,
'complete_registration' => 1 ]);
}
So how can I access the form request field from Updating function from observer to do a controller cleanup
Welcome to SO!
If you want to use Observers here, you should start by reading up on https://laravel.com/docs/5.8/eloquent#observers and https://laravel.com/docs/5.8/queues
This will likely work if you have all the data needed on your parent model, since you would just pass that model into the job that was triggered by the observer. If not, then observer/job might not be the best solution in your case. Instead I would probably create some sort of service, where you move the responsibility for creating these relationships. That way you can keep a clean controller level that only calls a service to create the models and then returns the result.
An example of this could be:
namespace App\Http\Controllers;
use App\Models\Something\SomeService;
class SomeController extends Controller
{
/**
* #var SomeService
*/
private $someService;
public function __construct(SomeService $someService)
{
$this->someService = $someService;
}
public function store()
{
$request = request();
$name = $request->input('name');
$something = $this->someService->create($name);
return response()->json(['data' => $something]);
}
}
namespace App\Models\Something;
class SomeService
{
public function create(string $name): Something
{
// Do whatever in here...
}
}
This is a simplified example of how I would do it. Hope it helps you a bit.
If you still want to use a job to take care of this, then I still don't think an observer is the right solution for you, as those are triggered on model events, such as created. This mean that you will not have access to the request object at that time, but only was was created (The model). Instead you could dispatch a job directly from the controller/service. That is all described in the queue link I posted at the top of the answer.

Laravel 5.1 ERROR Call to undefined function App\Http\Controllers\Auth\sendRegistermail()

I am trying to send automated mails via Mandrill in my Laravel 5.1 project. It was working but I was setting up my Mandrill Calls in my AuthController now I wanna have a class App\Marketing where all my functions for sending email will be stored. So in my controllers after an actions happens I can just call up the function with 1 line of code, but this line is giving me troubles I think.
my App\Marketing class looks like this now
class Marketing{
private $mandrill;
/**
* Via construct injection
*
*/
public function __construct(Mail $mandrill)
{
$this->mandrill = $mandrill;
}
public function sendRegistermail()
{
// In template content you write your dynamic content if you use <mc:edit> tags.
$template_content = [];
$message = array(
'subject' => 'Welkom bij SP*RK! - Jouw accountgegevens',
'from_email' => 'noreply#spark.com',
'from_name' => 'SP*RK',
'to' => array(
array(
'email' => $request->input('email'),
'name' => $request->input('name'),
'type' => 'to'
)
),
'merge_vars' => array(
array(
'rcpt' => $request->input('email'),
'vars' => array(
array(
'name' => 'NAME',
'content' => $request->input('name')
),
array(
'name' => 'EMAIL',
'content' => $request->input('email')
)
)
)
)
);
//email validation
if (str_contains($request['email'], "#kuleuven.be")) {
MandrillMail::messages()->sendTemplate('registration-mail', $template_content, $message);
} else {
MandrillMail::messages()->sendTemplate('registration-mail-notactive', $template_content, $message);
}
}
// ----- OR -------
/**
* Via method injection
*
*/
public function sendMail(Mail $mandrill, $data)
{
$mandrill->messages()->sendTemplate($data)
}
// ----- OR -------
/**
* Via the Facade
*
*/
public function sendMailByFacade($data)
{
\MandrillMail::messages()->sendTemplate($data);
}
}
This is how I try to call the function after registration in my postRegister function:
sendRegistermail();
return redirect($this->redirectPath());
sendRegistermail is a method of your Marketing class, you should call it on an instance of that object
So, first of all you have to create a Marketing object instance in your controller. A good way to do this it's by injecting the dependency in the constructor, like this:
//your controller class
class Controller
{
protected $marketing;
//Your controller's constructor
public function __construct(Marketing $marketing)
{
$this->marketing = $marketing;
}
}
Or you can use one of the other methods you have provided in your code to inject the instance.
Once you have an instance of the Marketing class, you only need to call the sendRegistermail method on that instance. In your controller method:
//call the method on the marketing instance
$this->marketing->sendRegistermail();

Phalcon php pass parameter in constructor

I would like to pass parameter to constructor in controller. Is it possible to do ?
I am trying to pass interface defination in constructor.
or is it possible to bind or set constructor in DI ?
below is my code.
<?php
use Phalcon\Repositories\IUsersRepository;
class UsersController extends ControllerBase
{
private $users;
public function __construct(IUsersRepository $usersRepository)
{
$this->users = $usersRepository;
}
?>
I have fixed by using below code in service.php
$di->set('usersRepository', array(
'className' => 'Phalcon\Repositories\UsersRepository'
));
$di->set('UsersController', array(
'className' => 'UsersController',
'arguments' => array(
array('type' => 'service', 'name' => 'usersRepository')
)
));
Yes you can.. take a look...
http://docs.phalconphp.com/en/latest/reference/di.html#instantiating-classes-via-the-service-container
If you want to send data on every request use dispatch Service
$di->set('IndexController', function() {
$component = new Component();
$component->private_method();
return $component;
}, true);
I wonder y u need this method!

CodeIgniter - Can not run $this->input->post(‘inputName’); in Modular Extensions

As my title, I tried call that method but I got an error:
Fatal error: Call to a member function post() on a non-object in C:\xampp\htdocs\cifirst\application\modules\front\controllers\shopping.php on line 11
If I create a controller not in module, that method I can use very easy but in this case can not (everything code in method below can not run). This is my code:
public function add_to_cart() {
$data = array(
'id' => $this->input->post('productId'), // line 11
'name' => $this->input->post('productName'),
'price' => $this->input->post('productPrice'),
'qty' => 1,
'options' => array('img' => $this->input->post('productImg'))
);
$this->load->library('MY_Cart');
$this->cart->insert($data);
//redirect($_SERVER['HTTP_REFERER']);
//echo $_POST['productId'].'-'.$_POST['productName'];
}
And this code doesn't work too:
public function __construct() {
$this->load->library('cart');
$this->load->helper('form');
}
I'm using XAMPP 1.8.1, CodeIgniter 2.1.3 and newest MX. Please help me!
When you're using CodeIgniter functions outside of controllers, models, and views you need to get an instance of Codeigniter first.
class MyClass {
private $CI;
function __construct() {
$this->CI =& get_instance();
$this->CI->load->library('cart');
$this->CI->load->helper('form');
}
public function someFunction() {
$var = $this->CI->input->post("someField");
}
}
If you are calling:
$this->input->post('productId');
inside controller than the problem is with your constructor declaration or your class name
Your construct part should contain code like this:
Class Home extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->CI->load->library('cart');
$this->CI->load->helper('form');
}
public function add_to_cart()
{
$data = array(
'id' => $this->input->post('productId'), // line 11
'name' => $this->input->post('productName'),
'price' => $this->input->post('productPrice'),
'qty' => 1,
'options' => array('img' => $this->input->post('productImg'))
);
}
}
It will work fine if you are calling from helpers function or any other classes than you should do something like this:
function __construct()
{
parent::__construct();
$this->CI->load->library('cart');
$this->CI->load->helper('form');
$this->CI =& get_instance();
}
public function add_to_cart()
{
$data = array(
'id' => $this->CI->input->post('productId'), // line 11
'name' => $this->CI->input->post('productName'),
'price' => $this->CI->input->post('productPrice'),
'qty' => 1,
'options' => array('img' => $this->CI->input->post('productImg'))
);
}

Categories