Symfony 2.7 retrieve root directory ANYWHERE - symfony

I just want to ask if there's a way to retrieve the root directory of a Symfony Application ANYHWERE?
What I mean by anywhere is, in any file of my App.
I've searched everywhere and all I get is this:
$this->get('kernel')->getRootDir();
Which of course works! But I can't use it in my custom classes. I need to get the root directory in one of my custom classes.
I've already read answers about DependencyInjection/Service and other stuff, but I think it's too complex/overkill to implement those just to solve my current problem.
I just want the root directory of my app, period. Is there any other way?

The simplest way I can think of is to define a constant in your app.php file, like this:
define("ROOTDIR", $kernel->getRootDir());
so you can then use this constant anywhere. Compared to this, a static method is overkill, too.

I reviewed my answer. Indeed, it will not fit your need. Anyway, if you don't want to use dependency injection to achieve this goal because you have static methods, where do you call these static methods? In a controller? In a command? In another service? If you don't want to instanciate your class because you don't want objects with their own data, you have 2 options:
Get the root directory outside your class, and use it as a parameter for your static methods.
If your class uses static methods that means your class behave as a helper class, it is just a tool (converter, exporter, renderer...etc). So I assume that you placed all your helper classes in one directory. In this case you can create a enum class which defines constant like root dir, web dir giving the absolute paths.

Related

Symfony: Dynamic configuration file loading

Here is the context :
Each user of my application belongs to a company.
Parameters for each company are defined inside "company.yml" configuration files, all of them sharing the exact same structure.
These parameters are then used to tweak the application behavior.
It may sound trivial, but all I'm looking for is the proper way to load these specific YAML files.
From what I understood so far, using an Extension class isn't possible, since it has no knowledge about current user.
Using a custom service to manage these configurations rather than relying on Symfony's parameters seems more appropriate, but I can't find how to implement validation (using a Configuration class) and caching.
Any help would be greatly appreciated, thanks for your inputs!
Using the Yaml, Processor and Configuration components of Symfony2 should fit your needs.
http://symfony.com/doc/current/components/yaml/introduction.html
http://symfony.com/doc/current/components/config/definition.html
Define your "CompanyConfiguration" class as if you were in the DependencyInjection case
Create a new "CompanyLoader" service
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Config\Definition\Processor;
$companies = Yaml::parse('company.yml');
$processor = new Processor();
$configuration = new CompanyConfiguration();
$processor->processConfiguration($configuration, $companies);
Now you should be able to use your companies array to do what you want
Have a look at http://symfony.com/doc/current/cookbook/configuration/configuration_organization.html as well as http://symfony.com/doc/current/cookbook/configuration/environments.html. If that's not the correct answer you'll have to be more specific on what your company.yml configuration contains.

What is best way to add additional object classes to my symfony2 controller files?

I'm relatively new to Symfony2, so I'm learning by doing. My controller classes are getting pretty big. I'd like to break it up with functions() or objects->method(). Unfortunately I can't figure out where to put the code. (actually its really simple functions... but I can wrap that in an object...)
--I can't add it to the bottom of my DefaultController.php file. It errors out, and not pretty code to boot, either inside or outside of the { }.
--I can't simply add a new NewObject.php file to the controller directory. That errors out. The error: FatalErrorException: ...NewObject not found.
--I've toyed with manual mods to ../app/autoload.php but that doesn't really make sense for a simple class add to my ./SRC/ bundle. Perhaps I should build a ./src/autoload.php file (similiar to ./vender/autoload.php) but the contents of that file don't make sense to me at all. I simply can't figure out how the AnnotationRegistry Loader works.
Am I missing something? This seems way too hard.. what I want is a wrapped up 'include' so I can use the class in dev and after deployment.
How do I include NewObject.php (and the accompanying $newObject->function() ) in my code?
I'm told I can add a service, yet that seems like outrageous overhead for such a seemingly simple task (again, all I'm trying to do is clean up my very long controller php code...)
thanks in advance for your advice.
So you've got a project structure that looks something like this, right?
project
-- app
-- bin
-- src
-- SomeName
-- SomeBundle
-- Controller
-- Entity
-- Resources
-- ...
-- vendor
-- web
And you're just looking to have some kind of "helper" class that's used throughout your bundle. Is that correct?
If so, then you can really put it wherever you want to inside your src/ directory... Just make sure that the class name matches the file name, and that the path to the file matches the namespace you define at the top of your PHP code.
Sometimes when I do this, I'll create a simple directory under my bundle called "Helper/". Other times, when the application is more complex, I might be a little bit more explicit. But here's what the first case would look like...
First, add your /Helper directory under your bundle, and create the class file:
project
-- app
-- bin
-- src
-- SomeName
-- SomeBundle
-- Controller
-- Entity
-- Helper
-- SomeHelper.php
-- Resources
-- ...
-- vendor
-- web
The contents of SomeHelper.php might look like this:
<?php
namespace SomeName\SomeBundle\Helper;
class SomeHelper
{
public function doSomething()
{
...
}
}
Because your namespace matches the file path, it gets autoloaded, so you don't need to worry about include statements. You can instantiate that class anywhere in your bundle, as long as you include a use statement:
<?php
namespace SomeName\SomeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use SomeName\SomeBundle\Helper\SomeHelper;
class DefaultController extends Controller
{
public function indexAction()
{
...
$helper = new SomeHelper();
$helper->doSomething();
...
}
}
Regarding the usage of services... Yes, that might be overkill, depending on what you're using it for. It's helpful to create services when the class needs to be aware of the application around it. For example, if you're creating a service that emails a User, it might want to access your database through the Doctrine service, or it might want to log the email activity through the Monolog service.
However, if your class doesn't need to know about the application (referred to as the "service container"), for example if it's just used to transfer data, then a helper class is probably more appropriate.

best approach to implement getRealPath()

I am working on struts 2.0 . I am designing a web application.
I am using Jasper Report in my application. I want to access the *.jrxml files in my action class. I don't want to give hard coded path to the files. So to get the path dynamically I googled it and got the solution that I can get the path using getRealPath() method. But I found two implementation of doing this:
Using HttpSession to get object of ServletContext and using the getRealPath() method of the ServletContext object.
Like this:
HttpSession session = request.getSession();
String realPath = session.getServletContext().getRealPath("/");
The second approach to do it directly using the static method getServletContext() of ServletActionContext. And then we can get the real path of the application using the getRealPath() method.
Like this:
String realPath = ServletActionContext.getServletContext().getRealPath("/");
Please tell me, is there any difference between the above two and also please tell me whether there is any other way to get the path?
Neither is "better", really, and I'd argue that neither is particularly good, either.
I might try getting the context path in an initialization servlet and stick it into the application context, then make your action(s) ApplicationAware and retrieve the value from the map.
This has the added benefit of aiding testability and removing the static references in the action.
That said, I see zero reason to go through the extra mechanics of your first approach: it adds a lot of noise for no perceivable benefit; I'm not even sure why it wuld be considered.
I'd also be a little wary of tying your actions to a path like this unless there's a real need, what's the specific use? In general you shouldn't need to access intra-app resources by their path.

How do I call GetLocalResource in another class

So I have Test1.aspx, Test1.aspx.vb. The LocalResource files, in the App_LocalResources folder, Test1.aspx.resx and Test1.aspx.es.resx. I also have a class called TestTheData.vb in the App_Code folder.
Now what I want to do is call GetLocalResource("stringObjRes").ToString in the TestTheData.vb class. The method however is not showing up in Intellisense. When I try to type manually, I get the error lines in my code.
I've imported:
Globalization
Threading
Threading.Thread
Web
Web.UI.Page.
No luck. So how I am supposed to do this....?
Well it seems that Local Resources can't be accessed in files that are in the App_Code folder. So I used Global Resources instead.
I know it's 1 year old but I just added the comment if some others are also searching for this:
Your guess is right, you cannot access the Local Resource Object from another class. GetLocalResourceObject only exists within the code of the page, in your case Test1.aspx.vb. If you are calling the class function from your Test1.aspx.vb you could of course retrieve the Local resource from there and then supply it to your TestTheData.vb as a parameter. But if you need the 'stringObjRes' in several places (not only in Test1.aspx) then a global resource is of course preferred. Details here: http://msdn.microsoft.com/en-us/library/ms227982(v=vs.100).aspx

Utility class or Common class in asp.net

Do anyone knows about the class which has the common function which we generally use while developing web application. I have no idea what you may call it, it may be the utility class or common function class. Just for reference, this class can have some common function like:
Generate Random number
Get the file path
Get the concatinated string
To check the string null or empty
Find controls
The idea is to have the collection of function which we generally use while developing asp.net application.
No idea what you are really asking, but there already are ready-made methods for the tasks you write in various library classes:
Random.Next() or RNGCryptoServiceProvider.GetBytes()
Path.GetDirectoryName()
String.Concat() or simply x + y
String.IsNullOrEmpty()
Control.FindControl()
Gotta love the intarwebs - An endless stream of people eager to criticize your style while completely failing to address the obvious "toy" question. ;)
Chris, you want to inherit all your individual page classes from a common base class, which itself inherits from Page. That will let you put all your shared functionality in a single place, without needing to duplicate it in every page.
In your example it looks like utility class - it is set of static functions.
But I think that you should group it in few different classes rather than put all methods in one class - you shouldn't mix UI functions(6) with string functions(3,4), IO functions (2) and math(1).
As Mormegil said - those functions exists in framework, but if you want to create your own implementations then I think that for part of your function the best solution is to create extension method.

Resources