Amazon SDK in Yii framework - yii

Trying to get the new Amazon SDK
http://docs.aws.amazon.com/aws-sdk-php/guide/latest/quick-start.html
in Yii Framework.
Amazon doc says to use like this:
// Include the SDK using the Composer autoloader
require 'vendor/autoload.php';
use Aws\S3\S3Client;
// Instantiate the S3 client with your AWS credentials
$s3Client = S3Client::factory(array(
'key' => 'YOUR_AWS_ACCESS_KEY_ID',
'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY',
));
But you can not use "use" in a method of a controller in Yii, so in Yii you can use setPathOfAlias to use namespaces.
I'm trying with this:
Yii::import('application.vendors.amazon-sdk.*');
Yii::setPathOfAlias('AwsSDK',Yii::getPathOfAlias('application.vendors.amazon-sdk.*'));
require 'aws-autoloader.php';
// Instantiate the S3 client with your AWS credentials
$aws = AwsSDK\Aws\Common\Aws::factory(array(
'key' => '************',
'secret' => '************',
));
It's loading the "Aws.php" correctly, but it says "Fatal error: Class 'AwsSDK\Aws\Common\Aws' not found"
What is the problem ?
Thank you

Is this for Yii 1.*?
In that case, just check how I configured it:
https://github.com/IvoRe/ES32
"But you can not use "use" in a method of a controller in Yii"
Aren't you supposed to use "use" at the top of a class? So the use declaration would come before the Controller declaration.
Quote from this tutorial:
Aliasing or importing should occur in the highest scope of a namespace
or in the global scope. Trying to do this in the scope of a method or
function is invalid syntax.

Related

Handling laravel api resource store and create endpoints

I have the following in my controller
class WrittersController extends Controller
{
public function index()
{
return view('backend.writters.dashboard');
}
public function store(Request $request){
//confused on when to use this
}
public function create(Request $request){
//add new user functionality
}
Now in my routes i would like to use the resource routes
Route::resource('writters','WrittersController');
Now the confusion comes in my vue axios http endpoints. I uderstand that i index is a get request but axios doesnt have a store or create point.
When should i use the store and create endpoints in the vuejs
UPDATE ON MY AXIOS. Am using axios via
axios.post("url") //how do i go about create and store here
The store function is called when you want to create i.e you will create and then store. So I usually call the create method from inside the store. I do this just to seperate the code and make it more readable. There is no store or create http requests. The store uses post request. So you will need to use post request with axios. Just use Route::resource in your web.php and then go to the terminal and check your routes with
php artisan routes (laravel 4)
php artisan route:list (laravel 5)
This will list all your registered routes and tell you which functions they use.
You use the other resources in the same way you used it for the get request.
Assuming your resource route looks like the following.
Route::resource('/mydata', 'MyDataController');
You would construct your requests in the following manner.
As you observed already, if you use axios.get('/mydata') you are routed to the index method. However if you use axios.post('/mydata'), Laravel will automatically route you to the store method.
If you want to use the create action you change the url to use axios.get('/mydata/create') and you are routed to the create method. Please note that the create action is not used for creating the record but rather for fetching the view where the user will create the record, e.g. a form. Then you will store the data entered in that form with a POST request.
If you want to use PUT (or PATCH) you use axios.put(/mydata/{some_id}) and you are routed to the update method.
So Laravel handles all the routing automatically for you depending on the type of request that is made (GET, POST, PUT/PATCH, DELETE). You only need to supply a parameter in the URL for those "Verbs" that require it.
Look at the documentation here link Look for the chart or table labeled "Actions Handled By Resource Controller" and you will see the various actions what verbs to access them with, and their respective URLs and Routes.
Also note that you can add custom methods to the resource controller if needed, but you will have to define the route. You do this by declaring the route in your routes file e.g. web.php before you declare the actual resource.
Say you want to add an new post method 'archived' to mark some record as being no longer active. You would do something like the following in your routes.
Route::post('/mydata/archived/{some_id}', 'MyDataController#archive');
Route::resource('/mydata', 'MyDataController');
As demonstrated above you can use axios.put() or axios.patch() and they will both be routed to the update method. There are times when you need to handle those requests differently. For example when using a autosave feature and I want to validate some form data when only one field has changed, I would use patch to validate just that single field as follows.
public function update(Request $request, $id)
{
if($request->isMethod('patch')){
$this->validateSingle($request);
}else{
$this->validateAll($request);
}
//....
}

Symfony - fallback to another application if Symfonfy app can not handle the request

We have an old Yii application along with new Symfony one.
The basic idea is simple - I need to check if there is a route matching in Symfony application then it is cool, if not then bootstrap Yii application and try to handle the request with it.
The main idea to not instantiate AppKernel (and do not load autoload.php - since there is two different autoload.php for each project) before I am sure there is route matching.
Can I do it somehow?
We've done this before with legacy applications.
There are two approaches you can take.
Wrap your old application inside a symfony project (recommended).
Unfortunately this will indeed load the symfony front-controller and kernel. No way around that. You need to make sure that symfony can't handle the request and to do that the kernel needs to be booted up.
Use sub-directories and apache virtual hosts to load one application vs the other as needed.
Given option 1,
You can either create your own front controller that loads either symfony or yii by reading routes (from static files if using yml or xml, or annotations which will be more complex) OR EventListener (RequestListener) that listens to the HttpKernelInterface::MASTER_REQUEST and ensures that a route can be returned.
Creating your own front controller is the only way that you can make it not load the symfony kernel, but it will require you to write something that understands the routes in both frameworks (or at least symfony's) and hands off the request appropriately.
Event listener example:
public function onkernelRequest(GetResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
... Code to continue normally, or bootstrap yii and return a custom response... (Can include and ob_start, or make an http request, etc)
}
public function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['onKernelRequest']
];
}
As you see, the kernel needs to be booted to ensure symfony can't serve the route. Unless creating your own front controller (as stated above).
A third approach would be to create a fallback controller, which would load up a specified URL if no route was found within symfony. Although this approach is generally used for legacy projects that lack a framework and use page scripts instead of proper routes, and definitely requires the use/help of output buffering.
The EventListener approach gives you the opportunity to create a proper Request to hand off to yii, and using what is returned to create a Response as proper symfony object (can also use ob or other options).
Thank you.
This is an alternative to vpassapera's solution -http://stovepipe.systems/post/migrating-your-project-to-symfony

Using Laravel's Mailgun driver, how do you (gracefully) send custom data and tags with your email?

So I'm using Laravel 5.1 and trying to integrate with Mailgun. Well, that's easy, but now I'm trying to send custom variables from my application along with my emails.
I'm actually switching our application over from Mandrill because of their "new direction" and such. With them, I could supply the variables and tags via the email headers, but with Mailgun, that only works when you send via SMTP. In Laravel, Mail::send() uses an API call, so in theory I'd add the metadata there with "v:my-custom-data" => "{"this_id": 123}", but I'd like to avoid altering core classes like that.
I also considered using Bogardo/Mailgun, but then I'd have to replace all the Mail::send()s with Mailgun::send(), and then I couldn't send emails locally (environment based email driver), and then the application would be "married" to Mailgun.
Anyone done this before? Please let me know if I'm not clear here.
I fixed my own problem. I was wrong, YOU CAN add custom variables via the SMTP method:
// Send email with custom variables and tags in Laravel
Mail::send('emails.blank',
['html' => 'This is a test of Mailgun. <strong>How did it work out?</strong>'],
function($message) {
$message->to('jack#mailinator.com');
$message->subject('Mailgun API Test');
$headers = $message->getHeaders();
$headers->addTextHeader('X-Mailgun-Variables', '{"msg_id": "666", "my_campaign_id": 1313}');
$headers->addTextHeader('X-Mailgun-Tag', 'test-tag');
});
My testing was just inadequate. Very good to know, however I think this is an undocumented feature, so I suggest using with caution.
Update for Laravel 5.4+
As you can read in the offical docs:
The withSwiftMessage method of the Mailable base class allows you to register a callback which will be invoked with the raw SwiftMailer message instance before sending the message. This gives you an opportunity to customize the message before it is delivered:
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$this->view('emails.orders.shipped');
$this->withSwiftMessage(function ($message) {
$message->getHeaders()
->addTextHeader('Custom-Header', 'HeaderValue');
});
}
You can just do like this in Laravel 5 :
Mail::send(['text' => 'my_template'], $data, function ($message) {
..
$message->getSwiftMessage()->getHeaders()->addTextHeader('X-Mailgun-Tag', 'my-tag');
});
Laravel implementation of the Mailgun Driver doesn't support options/parameters.
Here's a Gist which adds support to the native driver : https://gist.github.com/j0um/27df29e165a1c1e0634a8dee2122db99

Adding custom route to Zend REST controller

I am using Zend F/W 1.12 in order to build a REST server.
One of my requirements are to have an action that Is outside the boundaries of what Zend can recognize as a "Restfull" action. What I mean is that I would like to have an action that is called something like mymedia and would like tou routes requests that are directed to //mymedia . Currently, Zend understand it as the id to a getAction and off course this is not what I want.
Any help will be highly appreciated!
Thanks
The implementation of Zend_Rest_Route does not allow much customization but instead provides a rudimental routing scheme for out-of-the-box usage.
So if you need to change the way how URIs are interpreted you can extend Zend_Rest_Route, Zend_Controller_Router_Route_Module or Zend_Controller_Router_Route_Abstract class to create your own kind of routing.
Have a look at the match method of those classes and what they do - e.g. they populate the $_values property array (while respecting the $_moduleKey, $_controllerKey and $_actionKey properties).
You can then add it e.g. as the first route within your bootstrap class:
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$router->addRoute('myRoute', new My_Route($frontController));
$router->addRoute('restRoute', new Zend_Rest_Route($frontController));
See:
http://framework.zend.com/manual/1.12/en/zend.controller.router.html#zend.controller.router.basic
Routing is a simple process of iterating through all provided routes and matching its definitions to current request URI. When a positive match is found, variable values are returned from the Route instance and are injected into the Zend_Controller_Request object for later use in the dispatcher as well as in user created controllers. On a negative match result, the next route in the chain is checked.
I once wrote a custom route for zend framework 1 that can handle custom restful routes. it served me well until now. see https://github.com/aporat/Application_Rest_Controller_Route for more details.
for example, if you want to have a url such as /users/30/messages mapped correctly into a zend controller action, use this route in your bootstrap:
$frontController = Zend_Controller_Front::getInstance();
$frontController->getRouter()->addRoute('users-messages', new Application_Rest_Controller_Route($frontController, 'users/:user_id/messages', ['controller' => 'users-messages']));

How to use Ideone API in WSDL Format

I want to set up my own online compiler. I want to use Ideone Api for this. But its api is available in WSDL format. I tried very hard but could find any tutorial on how to extract data from WSDL. Please tell some way to use Ideone api.
Maybe a late answer but still may be useful for others. Here a simple example in PHP with it's native SOAP libray: http://ideone.com/3JBbt
Regretfully my server doesn't support PHP's SOAP library so I have used NuSOAP in the demo, now you have two ways to work with IDE One API.
Here a simple demo: http://rendon.x10.mx/files/ide1example/
And here is the code: http://rendon.x10.mx/files/ide1example.tar.gz
NOTE: You need provide your own user and password in ideone.php.
$params = array(
'user' => $user, // your user
'pass' => $pass, // your pass
'sourceCode' => $code,
'language' => $lang,
'input' => $input,
'run' => $run,
'private' => $private
);
For more info about the functions consult the API document: http://ideone.com/files/ideone-api.pdf
WSDL as name says, it describes functionality or the methods for communicating a webservice ,
As you said you have WSDL, then i would suggest you to create a WebService Client and start using it in your program.
For creating a WebService client, i would suggest you to use some tools such as Ex: http://cxf.apache.org/, they give you nice tools to create WS Clients like WS2js, WS2Java etc., kinda
As u've mentioned Ideone specifically , i'm working on it too, i would suggest you to look at creating a WSclient from WSDL in Netbeans(for this you need to download a plugin JAX-RPC)
or refer to this project http://code.google.com/p/ideone-cli/ , they've a working implementation of ideone WS Client.