Symfony2 Include Custom Configuration Variables - php

I'm using Symfony2 to access an API. I have a controller that initializes the Oauth and another that is for the Callback. Instead of manually typing out the api key, and other variables into these controllers, I want to have a single "configuration" file that I can include in all relevant locations (ie, the Oauth controller and OauthCallback controller).
How do I go about doing this? Should I add more lines to the config.yml or should I just create a new file called config.php and include it? With normal ol' php it'd be an easy require_once but since this is a framework, I want to make sure I'm doing it the "right" way.
Thanks!

Use parameters in parameters.yml or config.yml file.
parameters:
my_api_key: 1234
In controller get like that:
$apiKey = $this->container->getParameter('my_api_key');

IMO, you should write it in the config.yml. Remember that you can write other parameters and include it in the main config.yml with
imports:
- { resource: mi-file.extension}
In the controller, you can get this parameters with
$var= $this->container->getParameter('name_parameter');

Related

How do I read from a yml file in a controller in symfony2?

I have a random name.yml file inside lets say my src/AppBundle/Controller folder. The content inside the YML file is simple:
name: utkarsh
I need to access this from my controller, and have tried to fetch them with
$name = $this->getName('name');
from within my controller file. When I try this, I get this error message:
Attempted to call an undefined method named "getName" of class "AppBundle\Controller\DefaultController".
What is the correct way to do this?
If it's just going to be a general file, and wouldn't better be part of the framework's configuration (for example, in the parameters.yml file), you can parse/read the file using the Yaml component, which is already used by the Symfony framework.
use Symfony\Component\Yaml\Yaml;
$values = Yaml::parse(file_get_contents('/path/to/name.yml'));
echo $values['name'];
If the file you are loading is in the same directory as the code that is running it, you can use the PHP Automagic constants - __DIR__, file_get_contents(__DIR__ . '/name.yml'), or use it as a relative base to work from.
Don't just put your YML file in the Controllers folder. Instead, move your YML file into your bundles' config directory. See below,
AppBundle\Resource\config\abc.yml
Then, import this file in your services.yml file. See below,
imports:
- { resource: abc.yml }
And, make sure you abc.yml file will have a structure like this,
parameters:
name: utkarsh
Finally, you can access this parameter inside the Controller by calling like this,
$this->container->getParameter('name');
I hope this helps :)
Cheers!

Handle AJAX requests in separated directory/files

I want to move my all methods from controller, which are executed by AJAX request, to separate folder. For example create file UserBundle/Ajax/Ajax.php and put in this file, my all AJAX request methods.
Is it the right approach, to separate ajax requests, from normal http requests? I can't find any examples how to do it. It is possible in Symfony? I must extend Symfony\Bundle\FrameworkBundle\Controller\Controller in this Ajax.php file? That will be okay, that will be exist two folders in bundle Ajax and Controller, contains controllers but first for ajax request and second for normal http request?
Do You know any architectural pattern, for this problem?
I don't think there is any problem to do that, only make sure to define the routing path correctly:
An example for annotation routing:
# app/config/routing.yml
app_bundle:
resource: "#AppBundle/Controller"
type: annotation
prefix: /
app_bundle_ajax:
resource: "#AppBundle/Ajax"
type: annotation
prefix: /
I must extend Symfony\Bundle\FrameworkBundle\Controller\Controller in this Ajax.php file?
It's not mandatory, but the Symfony\Bundle\FrameworkBundle\Controller\Controller provide you excellent shortcuts like $this->json(...); since Symfony 3.1
You can create simple AjaxController as a service which will receive the ajax requests. Then you can redirect each of the requests to different Controllers and they will return JsonResponces().

Need Assistance with Symfony 2.7 creating first page

I am trying to learn the Symfony framework and struggling with it. The instructions are not very helpful or assume I know a lot more than I know. I am just trying to create a single web page with proper route and controller. I have been googling to find answers and made some progress but no luck yet. Right now I just have the standard install of Symfony with just default bundles etc. I created a project called "gtest3" and chose PHP for it...
I am not sure where I put the new route in (what file) or maybe it needs to be put in more than one file?
I found the "routing.yml" file which seems that is where I need to put it...
here is what is in there right now:
gtest3:
resource: "#gtest3Bundle/Resources/config/routing.php"
prefix: /
app:
resource: "#AppBundle/Controller/"
type: annotation
I am guessing I need to add something to this and put the location/filename of the controller? I have tried doing this a few ways and just get errors.
There is also the "routing.php" file that is referenced in the above code. I am not sure if this is the "controller" or if it is an additional piece of the "route". Here is the code from that file:
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('gtest3_homepage', new Route('/hello/{name}', array(
'_controller' => 'gtest3Bundle:Default:index',
)));
return $collection;
I am not sure what if anything I would add here.
Finally - there is the "DefaultConroller.php" file I found as well which may also be the controller. I dont think I need to include the code of that file here.
So - all I am trying to do is create a route of maybe "/gman" and then have the controller just echo something on the page. Super basic stuff. And I cannot figure out how to get this going.
Can anyone help with this? Thanks so much...
You can define your routes in three ways, either by using yml files, xml files, or by using a php file. This is documented behaviour.
You are from the looks of your routing.yml trying to set up a php version. I would not recommend it, and instead use configuration over coding the routing.
The annotation example would look like:
Adding a controller:
namespace Gtest3Bundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class Gtest3Bundle extends Controller
{
/**
* #Route("/hello/{name}")
* #Template()
*/
public function indexAction($name)
{
return array('name' => $name);
}
}
And add in your app/config/routing.yml:
gtest3:
resource: "#Gtest3Rights/Controller/"
type: annotation
prefix: /what-ever-you-want
You can check what kind of routes you have defined by using:
./app/console router:debug
If it doesn't appear hear, you have something misconfigured.
Please be advised that your bundle names breaks the convention of how bundles should be named in the symfony2 context.
It is advised to use NamespaceProjectBundle. This also documented. If you are stuck, try generating a bundle via the ./app/console generate:bundle. This way you can create a whole symfony2 structure which should show the default page hello/foo page just fine.
If it doesn't seem to run at all, make sure you have registered your bundle at the in the app/AppKernel.php file in the registerBundles() method.
To configure routes you can use yml, php or xml file. You can specify it in app/config/config.yml
framework:
router:
resource: "%kernel.root_dir%/config/routing.yml"
It's where you can check which file is used now.
There are some manners to store the routes.
app:
resource: "#AppBundle/Controller/"
type: annotation
This is how you use routes by writing annotations above your actions (eg indexAction) inside your controller class. Read more.
Another common approach is to build one or more .yml files inside each Bundle.
in app/config/routing.yml you should write this:
app:
resource: "#AppBundle/Resources/config/routing.yml"
prefix: /
Then you need to create the file (and directories if necessary) src/AppBundle/Resources/config/routing.yml and add the following content:
app_homepage:
path: /
defaults: { _controller: AppBundle:Default:index }
It will then try to find the DefaultController and fires the indexAction in the AppBundle (src/AppBundle/Controller/DefaultController.php).
To debug your routes simply type in your console from your projects directory:
app/console router:debug

How to pass a variable to routing defaults in Symfony?

I have a Symfony2 project with multiple brandings (subdomains). Each subdomain should use the same site functions and the same routes (with different hostname). Therefor I want to make the subdomain in the route path to a variable. Now it looks like:
mybundle_route:
resource: "#MyProjectBundle/Controller/"
type: annotation
prefix: /
host: "{subdomain}.%base_host%"
requirements:
subdomain: sub1|sub2
and the routing itself works. But if I try to generate some routes (e.g. in twig), I get following error because no subdomain variable is set:
Some mandatory parameters are missing ("subdomain") to generate a URL for route "company_route".
I don't want to add the parameter to each path() function in the project.
It works perfekt for one subdomain if I add the defaults like this:
defaults:
subdomain: sub1
but the routes are wrong for the other subdomains. Also it doesn't work with
defaults:
subdomain: "%subdomain%"
All I need is to pass the %subdomain% variable to the defaults or to set it somewhere in the controller constructor. But I can't find the way how it is going. I would appreciate any help.
If there is no better solution you could try to set %subdomain% parameter inside configuration file:
Create subdomain_parameter.php inside config folder.
Inside this file you have access to ther $container so you can manually retrieve current subdomain from the url and pass it to the container.
Import subdomain_parameter.php in the config.yml

In Symfony2 where is the correct place to store an app wide parameter?

I'd like to store a few application specific values for example:
a default Id number for a particular user choice if it's not set yet
keys/tokens/secrets for various services API's like facebook or flickr
Closest I've found so far is http://symfony.com/doc/2.0/cookbook/bundles/best_practices.html#configuration
If I used app/config/parameters.ini it would look like:
[flickr]
callbackUrl = http://example.com/approve
requestTokenUrl = http://www.flickr.com/services/oauth/request_token
consumerKey = 123a1237a29b123a5541232e0279123
[app]
default_layout = 2
these should be available in different bundles and also in templates
these should be available in different bundles and also in templates
They are. As long as you can access the container, you can access the parameters. From the docs you linked to:
$container->getParameter('acme_hello.email.from');
I think there's an error in your parameters.ini example. 'flickr' and 'app' shouldn't be wrapped in brackets. Also, the first element of parameters.ini should be [parameters].
Personally, I like using an app.yml file because I'm used to using it in Symfony 1.x projects (and because I don't see the reason for using an .ini file.). You can create app/config/app.yml and import it into your app/config/config.yml file like this:
imports:
- { resource: app.yml }
Your app.yml would look like this:
parameters:
flickr:
callbackUrl: http://example.com/approve
requestTokenUrl: http://www.flickr.com/services/oauth/request_token
consumerKey: 123a1237a29b123a5541232e0279123
app:
default_layout: 2
And this is how you would access data:
$container->getParameter('flickr.callbackUrl');
A third option is to define your parameters directly in app/config/config.yml. The code would be exactly the same as my example for app/config/app.yml. I don't recommend doing this though because app/config/config.yml can get pretty filled up with bundle configuration parameters, and I think it's cleaner to keep your own app params in a separate file. But of course, it's all up to you.

Categories