I have 'sendsms' function which i used it in one of my controllers and worked fine. now what i need to know how i can make class reference of this code to use it in other controllers, instead of copy/paste whole code in all controllers.
In other Q/A they mentioned about only creating reference but i wanted to do it properly like using constructor or etc, not just doing things work, i want to do it like real-world project.
Here's the code in controller :
public function store(Request $request)
{
$this->validate($request,[
'title' => 'required|string|min:6',
'gametype' => 'required|string|min:3',
'description' => 'required|string|min:1|max:180',
'price' => 'required|numeric|min:4',
'buyyer_id' => 'required|numeric|min:1'
// 'seller_id' => 'required|numeric|min:1'
]);
// return RequestModel::create([
// 'title' => $request['title'],
// 'description' => $request['description'],
// 'gametype' => $request['gametype'],
// 'price' => $request['price'],
// 'buyyer_id' => $request['buyyer_id'],
// 'seller_id' => Auth::user()->id,
// ]);
//
$requestModel = new RequestModel;
// store
$requestModel->title = $request['title'];
$requestModel->description = $request['description'];
$requestModel->gametype = $request['gametype'];
$requestModel->price = $request['price'];
$requestModel->buyyer_id = $request['buyyer_id'];
$requestModel->seller_id = Auth::user()->id;
$requestModel->save();
return $this->sendSms($request['title'], $request['gametype']);
}
// I want to use this code in another class to use it in all controllers without copy/paste it.
function sendSms($reqid, $recgametype) {
//Send sms to getway
//implement later.
$otp_prefix = ':';
$response_type = 'json';
$textMSGATLAS = iconv("UTF-8", 'UTF-8//TRANSLIT',"req : ( " .$reqid. " ) for ( " .$recgametype. " ) submitted ");
ini_set("soap.wsdl_cache_enabled", "0");
try {
$client = new SoapClient("http://xxxx");
$user = "user";
$pass = "pass";
$fromNum = "+xxx";
$toNum = "+xxxx";
$messageContent = $textMSGATLAS;
$op = "send";
$client->SendSMS($fromNum,$toNum,$messageContent,$user,$pass,$op);
} catch (SoapFault $ex) {
echo $ex->faultstring;
}
}
I'm right now learning and I'm beginner at this so help to understand how to make it work properly. Thanks.
You can create a separate SMS class like :
<?php
namespace App;
class SMS {
private $reqid;
private $recgametype;
public function __construct($reqid, $recgametype)
{
$this->reqid = $reqid;
$this->recgametype = $recgametype;
}
public function send()
{
$otp_prefix = ':';
$response_type = 'json';
$textMSGATLAS = iconv("UTF-8", 'UTF-8//TRANSLIT',"req : ( " .$this->reqid. " ) for ( " .$this->recgametype. " ) submitted ");
ini_set("soap.wsdl_cache_enabled", "0");
try {
$client = new SoapClient("http://xxxx");
$user = "user";
$pass = "pass";
$fromNum = "+xxx";
$toNum = "+xxxx";
$messageContent = $textMSGATLAS;
$op = "send";
return $client->SendSMS($fromNum,$toNum,$messageContent,$user,$pass,$op);
} catch (SoapFault $ex) {
throw new \Exception('SMS sending failed')
}
}
}
And then inside controller or wherever you would need :
public function sendSms($reqid, $recgametype) {
$sms = new \App\SMS($reqid, $recgametype);
$sms->send();
}
You can also create custom exception like SMSSendingFailedException and throw it instead of standard \Exception inside send() function.
That will help you to send appropriate response in controller like :
public function sendSms($reqid, $recgametype) {
try{
$sms = new \App\SMS($reqid, $recgametype);
$sms->send();
return response()->json('message' => 'SMS sent successfully', 200);
}
catch(SMSSendingFailedException $e){
return response()->json('message' => 'SMS sending failed', 500);
}
}
Then to go one step further, you can use concept of laravel facade if you need it all over the project with a quick class alias.
Related
I am coding in Laravel, How can I pass variable to one function to another function in Controller,
In controller file I have 2 functions like this
public function hiringEmployee(Request $request)
{
$hireEmployee = new EmployeeHire();
$hireEmployee->candidateName = $request->get('candidateName');
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/cv', $name);
$hireEmployee->file = $name;
$hireEmployee->save();
return redirect('list-candidate');
}
public function assignInterview(Request $request, $id)
{
$assignInterview = EmployeeHire::find($id);
$interview = $request->get('interview');
$assignto = $request->get('assignto');
$dateTime = $request->get('dateTime');
$note = $request->get('note');
$interviewDetails = ([
'interview' => $interview,
'assign_to' => $assignto,
'date_time' => $dateTime,
'note' => $note,
]);
$assignInterview->interview_details = $interviewDetails;
$assignInterview->save();
Mail::send('emails.hireemployee', ['candidateName' => $candidateName], function ($message) use ($assignto, $name) {
$message->subject('Interview For New Candidate!');
$message->from('hrm#wcg.com', 'HRM');
$message->to($mail);
$message->attach('uploads/cv/'.$name);
});
return redirect('list-candidate');
}
I want to use $candidateName and $name in assignInterview() function from hiringEmployee() function.
How can I do it?
You won't be able to use the $name and $candidateName directly from the other function as they look like they are for two different requests, however, it looks like you're saving that data to database when you're creating a new EmployeeHire in your hiringEmployee() method so you should already have access to that information in your assignInterview() method:
$assignInterview = EmployeeHire::find($id); // this is where you loading the model
$candidateName = $assignInterview->candidateName;
$name = $assignInterview->file;
In your situation , you can use two approach:
#1
Use Session Variable as below:
Session::put('candidateName', $candidateName);
Then:
$value = Session::get('candidateName');
#2
Use class attribute:
class acontroller extends Controller
{
private $classCandidateName;
}
You can try something like this:
public function hiringEmployee(Request $request)
{
$hireEmployee = new EmployeeHire();
$hireEmployee->candidateName = $request->get('candidateName');
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/cv', $name);
$hireEmployee->file = $name;
$hireEmployee->save();
return redirect('list-candidate');
}
public function assignInterview(Request $request, $id)
{
$assignInterview = EmployeeHire::find($id);
if(is_null($assignInterview)){
return redirect()->back()->withErrors(['Error message here']);
}
$interviewDetails = ([
'interview' => $request->get('interview'),
'assign_to' => $request->get('assignto'),
'date_time' => $request->get('dateTime'),
'note' => $request->get('note'),
]);
$assignInterview->interview_details = $interviewDetails;
$assignInterview->save();
Mail::send('emails.hireemployee', ['candidateName' => $assignInterview->candidateName], function ($message) use ($assignto, $assignInterview->file) {
$message->subject('Interview For New Candidate!');
$message->from('hrm#wcg.com', 'HRM');
$message->to($mail);
$message->attach('uploads/cv/'.$assignInterview->file);
});
return redirect('list-candidate');
}
Please, you should to be careful with find($id). If it is a null, you will get an error.
Have fun!
I am working on Joomla 3.6 and I am very new in joomla. I am fetching the data from an api and I want to pass that data to a view. How can I do that.
Controler: user.php
public function profile() {
$wskey = sdafsda;
$companycode = 'sdafsd';
$client = 1;
$cardno = 'sdafsd';
$pin = 'sdaf';
$wsdl = 'http://example/service.asmx?wsdl';
$getdata = array(
'WSKey' => $wskey,
'CompanyCode' => $companycode,
'CardNo' => $this->EncryptData($cardno),
'Client' => $client,
'PIN' => $this->EncryptData($pin),
);
$soapClient = new SoapClient($wsdl);
try {
$result = $soapClient->GetProfile($getdata);
} catch (Exception $e) {
return $e;
}
}
And view is created in com_users->views->cprofile.
I want to show this data in default.php of cprofile views and Want to know how can I call a view with data.
Sorry might not be clear.
I'm still trying to add a recaptcha to my website, I want try the recaptcha from Google but I can't use it properly. Checked or not, my email is still sent.
I tried to understand the code of How to validate Google reCaptcha v2 using phalcon/volt forms?.
But i don't understand where are my problems and more over how can you create an element like
$recaptcha = new Check('recaptcha');
My controller implementation :
<?php
/**
* ContactController
*
* Allows to contact the staff using a contact form
*/
class ContactController extends ControllerBase
{
public function initialize()
{
$this->tag->setTitle('Contact');
parent::initialize();
}
public function indexAction()
{
$this->view->form = new ContactForm;
}
/**
* Saves the contact information in the database
*/
public function sendAction()
{
if ($this->request->isPost() != true) {
return $this->forward('contact/index');
}
$form = new ContactForm;
$contact = new Contact();
// Validate the form
$data = $this->request->getPost();
if (!$form->isValid($data, $contact)) {
foreach ($form->getMessages() as $message) {
$this->flash->error($message);
}
return $this->forward('contact/index');
}
if ($contact->save() == false) {
foreach ($contact->getMessages() as $message) {
$this->flash->error($message);
}
return $this->forward('contact/index');
}
$this->flash->success('Merci, nous vous contacterons très rapidement');
return $this->forward('index/index');
}
}
In my view i added :
<div class="g-recaptcha" data-sitekey="mypublickey0123456789"></div>
{{ form.messages('recaptcha') }}
But my problem is after : i create a new validator for the recaptcha like in How to validate Google reCaptcha v2 using phalcon/volt forms? :
use \Phalcon\Validation\Validator;
use \Phalcon\Validation\ValidatorInterface;
use \Phalcon\Validation\Message;
class RecaptchaValidator extends Validator implements ValidatorInterface
{
public function validate(\Phalcon\Validation $validation, $attribute)
{
if (!$this->isValid($validation)) {
$message = $this->getOption('message');
if ($message) {
$validation->appendMessage(new Message($message, $attribute, 'Recaptcha'));
}
return false;
}
return true;
}
public function isValid($validation)
{
try {
$value = $validation->getValue('g-recaptcha-response');
$ip = $validation->request->getClientAddress();
$url = $config->'https://www.google.com/recaptcha/api/siteverify'
$data = ['secret' => $config->mysecretkey123456789
'response' => $value,
'remoteip' => $ip,
];
// Prepare POST request
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
],
];
// Make POST request and evaluate the response
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return json_decode($result)->success;
}
catch (Exception $e) {
return null;
}
}
}
So i don't know if tjis code is correct anyway, i have a problem too after that : how to create an object "recaptcha" in my form add
$recaptcha = new ?????('recaptcha');
$recaptcha->addValidator(new RecaptchaValidator([
'message' => 'Please confirm that you are human'
]));
$this->add($recaptcha);
PS: I apologize because i'm a noob here and my mother tongue is not english, so if you don't understand me or want give me some advices to create a proper question, don't hesitate ^^
I've made a custom form element for recaptcha. Used it for many projects so far.
The form element class:
class Recaptcha extends \Phalcon\Forms\Element
{
public function render($attributes = null)
{
$html = '<script src="https://www.google.com/recaptcha/api.js?hl=en"></script>';
$html.= '<div class="g-recaptcha" data-sitekey="YOUR_PUBLIC_KEY"></div>';
return $html;
}
}
The recaptcha validator class:
use Phalcon\Validation\Validator;
use Phalcon\Validation\ValidatorInterface;
use Phalcon\Validation\Message;
class RecaptchaValidator extends Validator implements ValidatorInterface
{
public function validate(\Phalcon\Validation $validation, $attribute)
{
$value = $validation->getValue('g-recaptcha-response');
$ip = $validation->request->getClientAddress();
if (!$this->verify($value, $ip)) {
$validation->appendMessage(new Message($this->getOption('message'), $attribute, 'Recaptcha'));
return false;
}
return true;
}
protected function verify($value, $ip)
{
$params = [
'secret' => 'YOUR_PRIVATE_KEY',
'response' => $value,
'remoteip' => $ip
];
$response = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?' . http_build_query($params)));
return (bool)$response->success;
}
}
Using in your form class:
$recaptcha = new Recaptcha($name);
$recaptcha->addValidator(new RecaptchaValidator([
'message' => 'YOUR_RECAPTCHA_ERROR_MESSAGE'
]));
Note 1: You were almost there, you just missed to create custom form element (the first and last code piece from my example);
Note 2: Also there is a library in Github: https://github.com/fizzka/phalcon-recaptcha I have not used it, but few peeps at phalcon forum recommended it.
I just can't seem to be able to solve this. I want to get the media:thumbnail from an RSS file . using ZF2 ; Zend\Frame a follow the manual but i cant get images from the xml file , any idea plz :)
that the controller Code :
<?php
namespace RSS\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Feed\Reader as feed;
class IndexController extends AbstractActionController
{
public function indexAction(){
try{
$rss = feed\Reader::import('http://www.wdcdn.net/rss/presentation/library/client/skunkus/id/cc3d06c1cc3834464aef22836c55d13a');
}catch (feed\Exception\RuntimeException $e){
echo "error : " . $e->getMessage();
exit;
}
$channel = array(
'title' => $rss->getTitle(),
'description' => $rss->getDescription(),
'link' => $rss->getLink(),
'items' => array()
);
foreach($rss as $item){
$channel['items'][] = array(
'title' => $item->getTitle(),
'link' => $item->getLink(),
'description' => $item->getDescription(),
// 'image' => $item->getImage(),
);
}
return new ViewModel(array(
'channel' => $channel
));
}
}
Hi
for who get the same pb i solve it by adding a new function to Zend/Feed/Reader/Entry/rss.php called getMedia() , that the code for who has a better idea or a better code i'll be thankful if you help :
public function getMedia()
{
if (array_key_exists('media', $this->data)) {
return $this->data['media'];
}
$media = null;
if ($this->getType() == Reader\Reader::TYPE_RSS_20) {
$nodeList = $this->xpath->query($this->xpathQueryRss . '/media:thumbnail');
if ($nodeList->length > 0) {
$media = new \stdClass();
$media->url = $nodeList->item(0)->getAttribute('url');
}
}
$this->data['media'] = $media;
return $this->data['media'];
}
Here is a way to do it without having to extend or modify the class:
foreach ($channel as $item) {
$xmlItem = $item->saveXml();
$xmlFeed = new \SimpleXMLElement($xmlItem);
$thumbAttr = $xmlFeed->children('http://search.yahoo.com/mrss/')->thumbnail->attributes();
$thumbUrl = (string)$thumbAttr['url'];
}
I am trying to get a soap response in php. It keeps coming as an object onto my web browser but not as xml. WSDL shows as XML but not the response received. Below is my server side code. The soap server is Zend Soap
ini_set("soap.wsdl_cache_enabled", 0);
if (isset($_GET['wsdl'])){
$wsdl = 'http://localhost/webservice/soap';
$autoDiscover = new AutoDiscover();
$autoDiscover->setOperationBodyStyle(
array('use' => 'literal',
'namespace' => 'http://localhost/webservice/soap')
);
$autoDiscover->setBindingStyle(
array('style' => 'rpc',
'transport' => 'http://schemas.xmlsoap.org/soap/http')
);
$autoDiscover->setComplexTypeStrategy(new ArrayOfTypeComplex());
// $service is the class that does the handling of functions
$autoDiscover->setClass($service);
$autoDiscover->setUri($wsdl);
$response->getHeaders()->addHeaderLine('Content-Type', 'text/xml');
$response->setContent($autoDiscover->toXml());
} else {
$server = new Server('http://localhost/webservice/soap?wsdl'
);
// $service is the class that does the handling of functions
$server->setObject($service);
$response->setContent($server->handle());
}
return $response;
}
Service class
class service
{
/**
*
* #param string $Email
* #return int $Credit
*/
public function checkCredits($Email)
{
$validator = new email();
if (!$validator->isValid($Email))
{
return new \SoapFault('5', 'Please Provide an Email');
}
$rowset = $this->tableGateway->select(array('EMAIL'=>$Email))
$row = $rowset->current();
$credits = $row->CREDITS;
return $credits;
}
}
Request is :
try{
$sClient = new SoapClient('http://localhost/webservice/soap?wsdl');
$params = "email";
$response = $sClient->checkCredits($params);
var_dump($response);
} catch(SoapFault $e){
var_dump($e);
}
This is an example of how I handle my functions with SoapClient:
$client = new SoapClient('http://url/Service.svc?wsdl');
$var = array('arg' => 10,
'VA' => 48);
$varresponse = $client->Function($var);
print_r( $varresponse->FunctionResult);
Hope this will help you out.
Your soapserver should look a bit like this:
<?php
if(!extension_loaded("soap")){
dl("php_soap.dll");
}
ini_set("soap.wsdl_cache_enabled","0");
$server = new SoapServer("hello.wsdl");
function doHello($yourName){
return "Hello, ".$yourName;
}
$server->AddFunction("doHello");
$server->handle();
?>
How did you set up yours? Do you return anything?
Now, your client should look like this:
<?php
try{
$sClient = new SoapClient('http://localhost/test/wsdl/hello.xml');
$params = "Name";
$response = $sClient->doHello($params);
var_dump($response);
} catch(SoapFault $e){
var_dump($e);
}
?>