In my application architecture I want to replace my globals with something that ain't gonna burn most of the developer's eyes, because I am using globals like this,
define('DEVELOPMENT_ENVIRONMENT', true);
// Shorten DIRECTORY_SEPARATOR global,
define('DS', DIRECTORY_SEPARATOR);
// Set full path to the document root
define('ROOT', realpath(dirname(__FILE__)) . DS);
how could I prevent this? I tried creating a class that reads an xml file, but this will give me a longer code like this
$c = new Config();
if($c->devmode === TRUE) {}
or maybe something like this
$c = new Config()
echo $c->baseurl;
Any better ways to do this?
I think questions like yours can not be generally answered but they probably deserve an answer anyway. It's just that there is not the one golden rule or solution to deal with this.
At the most bare sense I can imagine the problem you describe is the context an application runs in. At the level of human face this is multi-folded, just only take the one constant:
define('DEVELOPMENT_ENVIRONMENT', true);
Even quite simple and easily introduced, it comes with a high price. If it is already part of your application first try to understand what the implications are.
You have one application codebase and somewhere in it - in concrete everywhere the constant is used - there are branches of your code that are either executed if this constant is TRUE or FALSE.
This on it's own is problematic because such code tends to become complex and hard to debug. So regardless how (constant, variable, function, class) you first of all should reduce and prevent the usage of such constructs.
And honestly, using a (global) constant does not look that wrong too me, especially compared with the alternatives, it first of all is the most preferable one in my eyes because it lies less and is not complicated but rather straight forward. You could turn this into a less-dynamic constant in current PHP versions by using the const keyword to declare it however:
const DEVELOPMENT_ENVIRONMENT = TRUE;
This is one facet of this little line of code. Another one is the low level of abstraction it comes with. If you want to define environments for the application, saying that a development environment is true or false is ambiguous. Instead you normally have an environment which can be of different types:
const ENVIRONMENT_UNSPECIFIED = 0;
const ENVIRONMENT_DEVELOPMENT = 1;
const ENVIRONMENT_STAGING = 2;
const ENVIRONMENT_LIVE = 3;
const ENVIRONMENT = ENVIRONMENT_DEVELOPMENT;
However this little example is just an example to visualize what I mean to make it little ambiguous. It does not solve the general problem outlined above and the following one:
You introduce context to your application on the level of global. That means any line of code inside a component (function, class) that relates to anything global (here: DEVELOPMENT_ENVIRONMENT) can not be de-coupled from the global state any longer. That means you've written code that only works inside that applications global context. This stands in your way if you want to write re-usable software components. Re-usability must not only mean a second application, it already means in testing and debugging. Or just the next revision of your software. As you can imagine that can stand in your own way pretty fast - or let's say faster then you want.
So the problem here is less the constant on it's own but more relying to the single context the code will run in or better worded global static state. The goal you need to aim for when you would like to introduce changes here for the better is to reduce this global static state. This is important if you're looking for alternatives because it will help you to do better decisions.
For example, instead of introducing a set of constants I have in the last code-example, find places that you make use of DEVELOPMENT_ENVIRONMENT and think why you have put it in there and if it is not possible to remove it out there. So first think about if it is needed at all (these environment flags are often a smell, once needed in a quick debugging or because it was thought "oh how practical" - and then rotting in code over weeks of no use). After you've considered whether it is needed or not and you came to the point it is needed, you need to find out why it is needed at that place. Does it really belong there? Can't it - as you should do with anything that provides context - turned into a parameter?
Normally objects by definition ship with their own context. If you've got a logger that behaves differently in development than in live, this should be a configuration and not a decision inside the application code somewhere. If your application always has a logger, inject it. The application code just logs.
So as you can imagine, it totally depends on many different things how and when you can prevent this. I can only suggest you to find out now, to reduce the overall usage.
There are some practical tips on the way for common scenarios we face in applications. For the "root-path problem" you can use relative paths in conjunction with magic constants like __DIR__. For example if the front-endpoint in the webroot (e.g. index.php) needs to point to the private application directory hosting the code:
<?php
/**
* Turbo CMS - Build to race your website's needs to the win.
*
* Webroot Endpoint
*/
require(__DIR__ . '/../private/myapp/bootstrap.php');
The application then normally knows how it works and where to find files relative to itself. And if you return some application context object (and this must not be global(!)), you can inject the webroot folder as well:
<?php
/**
* Turbo CMS - Build to race your website's needs to the win.
*
* Webroot Endpoint
*/
/* #var $turboAppContext Turbo\App\WebappContext */
$turboAppContext = require(__DIR__ . '/../private/myapp/bootstrap.php');
$turboAppContext->setWebroot(__DIR__);
Now the context of your webserver configures the application defaults. this is a crucial part actually because this touches a field of context inside your application (but not in every component) that is immanent. You can not prevent this context. It's like with leaking abstractions. There is an environment (known as "the system") your application runs in. But even though, you want to make it as independent as possible.
Like with the DEVELOPMENT_ENVIRONMENT constant above, these points are crucial to reduce and to find the right place for them. Also to only allow a very specific layer to set the input values (to change context) and only some high-level layers of your software to access these values. The largest part of your code-base should work without any of these parameters. And you can only control the access by passing around parameters and by not using global. Then code on a level that is allowed to access a certain setting (in the best meaning of the word), can access it - everything else does not have that parameter. To get this safety, you need to kill globals as best as possible.
E.g. the functionalitly to redirect to another location needs the base-url of the current request. It should not fetch them from server variables but based on a request-object that abstracts access to the server variables so that you can replace things here (e.g. when you're moving the application behind a front-proxy - well not always the best example but this can happen). If you have hard-coded your software against $_SERVER you would then need to modify $_SERVER in some stages of your software. You don't want that, instead you move away from this (again) global static state (here via a superglobal variable, spot those next to your global constants) by using objects that represent a certain functionality your application needs.
As long as we're talking about web-applications, take a look at Symfony's request and response abstraction (which is also used by many other projects which makes your application even more open and fluent). But this is just a side-note.
So whatever you want to base your decision on, do not get misguided by how many letters to type. The benefit of this is very short-sighted when you start to consider the overall letters you need to type when developing your software.
Instead understand where you introduce context, where you can prevent that and where you can't. For the places you can't, consider to make context a parameter instead of a "property" of the code. More fluent code allows you more re-usable code, better tests and less hassles when you move to another platform.
This is especially important if you have a large installation base. Code on these bases with global static state is a mess to maintain: Late releases, crawling releases, disappointed developers, burdensome development. There are lessons to learn, and the lessons are to understand which implications certain features of the language have and when to use them.
The best rule I can give - and I'm not an academic developer at all - is to consider global as expensive. It can be a superb shortcut to establish something however you should know about the price it comes with. And the field is wide because this does not only apply to object oriented programming but actually to procedural code as well. In object oriented programming many educational material exists that offers different ways to prevent global static state, so I would even say the situation there is quite well documented. But PHP is not purely OOP so it's not always that easy as having an object at hand - you might first need to introduce some (but then, see as well the request and response abstractions that are already available).
So the really best suggestion I can give to improve your code in context of this question is: Stick to the constant(s) (maybe with const keyword to make them less dynamic and more constant-ly) and then just try to remove them. As written in comments already, PHP does a very fine job about cross-platform file-access, just use / as directory separator, this is well understood and works very well. Try to not introduce a root-path constant anyway - this should not be constant for the code you write but a parameter on some level - it can change, for example in sub-requests or sub-apps which can save you a life-span before re-inventing the wheel again.
The hard task is to keep things simple. But it's worth.
Just put some server variable to the vhost config and prepare different config files for each option. Using apache it would be (you'll need mod_env module):
SetEnv ENVIRONMENT dev
And then in index just use something like:
$configFileName = getenv ('ENVIRONMENT').'.ini';
Now just load this file and determine all the application behaviour on the values given. Ofcourse you can facilitate it further if you use some framework but this would be a good start.
You can encapsulate your constants in a class and then retrieve it by a static methods :
if(Config::devMode()) {}
echo Config::baseUrl();
This way you save a line and some memory because you don't need to instantiate an object.
Related
When should I use what?
I have the option to define constants in the index.php entry script file like it is recommended in Yii2 guide: constants. Or I could use the params in the configuration - explained in YII2 guide: params. Both are per application and not really global.
Currently, it seems to me that params are a bit less comfortable if I want to combine values like this:
define('SOME_URL', 'http://some.url');
define('SOME_SPECIALIZED_URL', SOME_URL . '/specialized');
Besides, accessing is bit more code (Yii::$app->params['something']) compared to constants.
So when should or could I use what?
Small update: in PHP 7 define() supports arrays as well, so the whole params structure can be configured as a constant. Probably better supported by IDEs.
I tend to use the Yii application parameters. The main reason for this is the values held in these kind of parameters tend to change depending on the environment that the code is run in. So I will have a build system that runs (I use Phing) and pulls in settings from a non-version controlled file such as build.properties.
So any dev database settings, dev domain settings, api sandbox addresses etc will be loaded in in my development environment and the correct production values will be used when a build is run on a live server.
If you were settings these values in some kind of php file, then tracking with version control becomes problematic because each time you build in your dev environment changes would be made to your index.php file. Someone might even end up committing these changes in by mistake.
So in summary, I would say if they are true constants - the same in any environment in which the code runs - they maybe a constant is fine. If these values might change, depending on where the code is run, then my preference is to place them in params and let your build system load them from a non-version controlled file.
The main disadvantage (and advantage at the same time) of constants is that they're... constant. Once you set it, you can't change it. This is the only thing that should matter here. You should use constants for values that should never change during execution, and params for everything else.
Constants may be a real PITA when you start writing tests for your app. It will show you that many things that you considered as constant are not really constant. At this point params are more flexible - you can easily change them or adjust at configuration level using merging of configuration arrays. Using constants may drive you into a trap of unconfigurable application that cannot be installed on different environment without modification of hardcoded constant.
Besides, accessing is bit more code (Yii::$app->params['something']) compared to constants.
This is completely irrelevant. As a programmer you spend less than 5% of your time on actually writing a code. Additional 10 keystrokes will do not make any difference. You should always think about it in terms of readability. You write code once and read it hundreds of times, so it is much more important how much time you will need to read and understand code than the time you spent on writing it. And using known conventions (and Yii::$app->params is one of them) makes your code easier to understand, especially for other programmers.
But if you really want to write less code, you can always create a wrapper function for short access to params.
function p($name) {
return Yii::$app->params[$name];
}
echo p('my-param');
I designed a PHP 5.5+ framework comprised of more than 750 different classes to make both web applications and websites.
I would like to, ideally, be able to reduce its size by producing a version of itself containing just the bare essential files and resources needed for a given project (whether it's a website or a web application).
What I want to do is to be able to:
reduce the amount of traits, classes, constants and functions to the bare essential per project
compress the code files to achieve a lesser deployment size and faster execution (if possible)
So far, I've got the second part completed. But the most important part is the first, and that's where I'm having problems. I have a function making use of get_declared_classes() and get_declared_traits(), get_defined_constants() and get_defined_functions() to get the full list of user-defined classes, traits, functions and constants. But it gives me pretty much EVERYTHING and that's not what I want.
Is there a way to get all defined classes, functions and constants (no need for traits as I could run class_uses() on every class and get the list of traits in use by that class) for a single given script?
I know there's the token_get_all() function but I tried it with no luck (or maybe it's I'm using it the wrong way).
Any hint? Any help would be greatly appreciated :)
You can use PHP Parser for this. It constructs abstract syntax trees based on the files you supply to it. Then you can analyze its output for each file, and produce a report usable to you.
Other than that, you can use token_get_all() approach you've mentioned already, and write a small parser yourself. Depending on your project, this might be easier or more difficult. For example, do you use a lot of new X() constructs, or do you tend to pass dependencies via constructors?
Unfortunately, these are about the only viable choices you have, since PHP is dynamically typed language.
If you use dependency injection, however, you might want to take a look at your DI framework's internal cache files, which often contain such dependency maps. If you don't use such framework, I recommend to start doing this, especially since your project is big and that's where dependency injection excels at. PHP-DI, one of such frameworks, proved to be successful in some of my middle-size projects (25k SLOC).
Who knows? Maybe refactoring your project to use DI will let you accomplish the task you want without even getting to know all the dependencies. One thing I'm sure of is that it will help you maintain it.
Does anyone have any tutorials that are up to date, and include more complex processing of rules? Most of the tutorials I am finding on line do not deal with 1.4.3, with the ruleset.xml, but the old php file of coding.
Secondly, I want to do more in-depth processing as our company has different coding standards that I need to code for an enforce, and want a good starting place to understand the existing complex sniffs, and the structures therein.
Our company uses different standards than the common libraries so that when reading the code, the developer knows if the method is from an external library (PEAR/Zend/etc...) as the naming convention will indicate that. If the coding standard is not our format, then the method is from an outside library, and chances are good it works well, without the need for the developer to re-implement something.
In larger code bases, you will see a class created and methods referenced, without knowing the sources anymore, without tracing up the stack. Therefore, by using different standards, are classes will stand out.
For instance:
$Foo = Foo::Find(); // Mixed case - from a library or PHP itself
$Bar = BAR::Find(); // All uppercase - ours, may need to optimize the Find()
Variable declarations are the same, where we use a trailing underscore on methods and variables to indicate Private scope. If someone is changing the scope resolution, they would remove the underscore, and the change/remove private keyword to clearly indicate that they understood the ramifications of their change.
Start here, but it is basic: http://pear.php.net/manual/en/package.php.php-codesniffer.coding-standard-tutorial.php
PHP_CodeSniffer comes with quite a lot of sniffs that do a lot of different things. It might be worth looking through some of those to see how they make use of the token stack.
Using the -vv command line argument is also a really good way to see how a file is converted into tokens. This will help you register to look for the correct token types and make use of the $phpcsFile->findNext() and $phpcsFile->findPrevious() methods that many sniffs use.
Here is a small sniff that might be worth looking at:
https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/PSR2/Sniffs/ControlStructures/ElseIfDeclarationSniff.php
And another that shows the usage of additional indexes in the token stack:
https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/PSR2/Sniffs/ControlStructures/ControlStructureSpacingSniff.php
Note: Configuration are being kept in a PHP file, config.php.
I've seen this done differently, here's a short list of examples (I'm storing DB info in these examples):
Constants: global, readonly
define('DB_USER','user12');
define('DB_PASS','21user');
Using GLOBALS array: global, changeable, repetitive, mixed with other globals
$GLOBALS['DB_USER']='user12';
$GLOBALS['DB_PASS']='21user';
Using a non-global array but raised globaly: possibly worse than the 2nd option
$config=array(); ...
$config['DB_USER']='user12';
$config['DB_PASS']='21user';
... global $config;
mysql_connect('localhost',$config['DB_USER'],$config['DB_PASS']);
Defining class properties: (global, enumerable)
class Config {
public $DB_USER='user12';
public $DB_PASS='21user';
}
Criteria/Options/Features:
ease of coding: you wouldn't want to check if the setting exists, or initialize it
ease of modification: a non-programmer/layman could easily modify the settings
stored in a clean place: not mixed with other variables (can be stored in a sub-array)
runtime modification: in some cases, other devs may easily modify existing settings
The configuration might need to be changed some time during the running of the system, so option 1 is already not viable. The third option is not too clean either.
While writing this, I'm getting a big warning on the discussion being subjective and closed. So please keep up to the topic and give valid reasons to your answers.
This is a pretty obvious question, and considering I'm well familiar with different answers, you might ask, why am I making all this fuss? The thing is, I'm developing a framework, and unlike another framework (*ahem* joomla *ahem*) I don't want to pass through their mistake of throwing in a miss-informed solution which ends up having to be changed/re-purposed in the future.
Edit: First of, the location of the config file does not concern me. I'll make sure people can easily change location, if they want to, but this will not be a requirement.
First of, cheap webhosts does not allow doing this, secondly, as far as security goes, this is really not a good option. Why? Because, the framework needs to know where the config is. Really, security through obscurity does not work. I'd rather fix all RFI and XSS (for instance) than be paranoid on hiding the config file under several layers.
Hard-coded data may not be an option where people doing reconfiguration are not code-adept. Consider using parse_ini_file().
Why not use Zend_Config? It creates a common interface for configuration options that can be stored in a confing file or a database (with a proper adapter). And it's lightweight; you don't have to bring in the entire Zend framework to use it.
BTW, since you're building a framework, you should keep pollution of the global namespace to a minimum. Something like your 3rd option, and if you're targeting 5.3 exclusively, look at using proper namespaces.
A bit late, but this might be of interest to you: http://milki.include-once.org/genericplugins/genconfig.html
It provides a simple API to edit PHP config files in-place. It keeps comments and other code in-tact. And it allows for a global $config array/ArrayObject and defining constants. It operates almost automatically if combined with plugin configuration comments. However, it's a lot of code. But maybe worth checking out for the concept. (I'm also using a readable config.php, as it seems the most useful configuration format for me.)
Put in a common file and include it every where you need. The benefit when you go live or move to your test server you just need to edit just this one file and all configs are changed. Method 2 is better as it allows you to change it.
Remember once you connect to mysql if you need to change the user and pass you have to re-connect
This question already has answers here:
Stop using `global` in PHP
(6 answers)
Closed 4 months ago.
function foo () {
global $var;
// rest of code
}
In my small PHP projects I usually go the procedural way. I generally have a variable that contains the system configuration, and when I nead to access this variable in a function, I do global $var;.
Is this bad practice?
When people talk about global variables in other languages it means something different to what it does in PHP. That's because variables aren't really global in PHP. The scope of a typical PHP program is one HTTP request. Session variables actually have a wider scope than PHP "global" variables because they typically encompass many HTTP requests.
Often (always?) you can call member functions in methods like preg_replace_callback() like this:
preg_replace_callback('!pattern!', array($obj, 'method'), $str);
See callbacks for more.
The point is that objects have been bolted onto PHP and in some ways lead to some awkwardness.
Don't concern yourself overly with applying standards or constructs from different languages to PHP. Another common pitfall is trying to turn PHP into a pure OOP language by sticking object models on top of everything.
Like anything else, use "global" variables, procedural code, a particular framework and OOP because it makes sense, solves a problem, reduces the amount of code you need to write or makes it more maintainable and easier to understand, not because you think you should.
Global variables if not used carefully can make problems harder to find. Let's say you request a php script and you get a warning saying you're trying to access an index of an array that does not exist in some function.
If the array you're trying to access is local to the function, you check the function to see if you have made a mistake there. It might be a problem with an input to the function so you check the places where the function is called.
But if that array is global, you need to check all the places where you use that global variable, and not only that, you have to figure out in what order those references to the global variable are accessed.
If you have a global variable in a piece of code it makes it difficult to isolate the functionality of that code. Why would you want to isolate functionality? So you can test it and reuse it elsewhere. If you have some code you don't need to test and won't need to reuse then using global variables is fine.
I agree with the accepted answer. I would add two things:
Use a prefix so you can immediately identify it as global (e.g. $g_)
Declare them in one spot, don't go sprinkling them all around the code.
Who can argue against experience, college degrees, and software engineering? Not me. I would only say that in developing object-oriented single page PHP applications, I have more fun when I know I can build the entire thing from scratch without worrying about namespace collisions. Building from scratch is something many people do not do anymore. They have a job, a deadline, a bonus, or a reputation to care about. These types tend to use so much pre-built code with high stakes, that they cannot risk using global variables at all.
It may be bad to use global variables, even if they are only used in the global area of a program, but let's not forget about those who just want to have fun and make something work.
If that means using a few variables (< 10) in the global namespace, that only get used in the global area of a program, so be it. Yes, yes, MVC, dependency injection, external code, blah, blah, blah, blah. But, if you have contained 99.99% of your code into namespaces and classes, and external code is sandboxed, the world will not end (I repeat, the world will not end) if you use a global variable.
Generally, I would not say using global variables is bad practice. I would say that using global variables (flags and such) outside of the global area of a program is asking for trouble and (in the long run) ill-advised because you can lose track of their states rather easily. Also, I would say that the more you learn, the less reliant you will be on global variables because you will have experienced the "joy" of tracking down bugs associated with their use. This alone will incentivize you to find another way to solve the same problem. Coincidentally, this tends to push PHP people in the direction of learning how to use namespaces and classes (static members, etc ...).
The field of computer science is vast. If we scare everyone away from doing something because we label it bad, then they lose out on the fun of truly understanding the reasoning behind the label.
Use global variables if you must, but then see if you can solve the problem without them. Collisions, testing, and debugging mean more when you understand intimately the true nature of the problem, not just a description of the problem.
Reposted from the ended SO Documentation Beta
We can illustrate this problem with the following pseudo-code
function foo() {
global $bob;
$bob->doSomething();
}
Your first question here is an obvious one
Where did $bob come from?
Are you confused? Good. You've just learned why globals are confusing and considered a bad practice. If this were a real program, your next bit of fun is to go track down all instances of $bob and hope you find the right one (this gets worse if $bob is used everywhere). Worse, if someone else goes and defines $bob (or you forgot and reused that variable) your code can break (in the above code example, having the wrong object, or no object at all, would cause a fatal error). Since virtually all PHP programs make use of code like include('file.php'); your job maintaining code like this becomes exponentially harder the more files you add.
How do we avoid Globals?
The best way to avoid globals is a philosophy called Dependency Injection. This is where we pass the tools we need into the function or class.
function foo(\Bar $bob) {
$bob->doSomething();
}
This is much easier to understand and maintain. There's no guessing where $bob was set up because the caller is responsible for knowing that (it's passing us what we need to know). Better still, we can use type declarations to restrict what's being passed. So we know that $bob is either an instance of the Bar class, or an instance of a child of Bar, meaning we know we can use the methods of that class. Combined with a standard autoloader (available since PHP 5.3), we can now go track down where Bar is defined. PHP 7.0 or later includes expanded type declarations, where you can also use scalar types (like int or string).
As:
global $my_global;
$my_global = 'Transport me between functions';
Equals $GLOBALS['my_global']
is bad practice (Like Wordpress $pagenow)... hmmm
Concider this:
$my-global = 'Transport me between functions';
is PHP error But:
$GLOBALS['my-global'] = 'Transport me between functions';
is NOT error, hypens will not clash with "common" user declared variables, like $pagenow. And Using UPPERCASE indicates a superglobal in use, easy to spot in code, or track with find in files
I use hyphens, if Im lazy to build classes of everything for a single solution, like:
$GLOBALS['PREFIX-MY-GLOBAL'] = 'Transport me ... ';
But In cases of a more wider use, I use ONE globals as array:
$GLOBALS['PREFIX-MY-GLOBAL']['context-something'] = 'Transport me ... ';
$GLOBALS['PREFIX-MY-GLOBAL']['context-something-else']['numbers'][] = 'Transport me ... ';
The latter is for me, good practice on "cola light" objectives or use, instead of clutter with singleton classes each time to "cache" some data. Please make a comment if Im wrong or missing something stupid here...