Is there a standard way of dealing with globally scoped variables in PHP? Session scoped?
From the research I've done, it looks like the options are mostly add-ons or external. APC might work, but would be limited to a single PHP instance and not so useful for a farm of servers. Memcached seems like it would work, but I was hoping to find something within PHP.
Does its stateless approach keep there from being a standard method for handling this?
A persistent layar is the only way to go with php. Either file based solution or database.
php natively doesn't provide any mechanism to do application scope variable.
You can do session variables with $_SESSION.
Related
I want some of the $GLOBALS['TYPO3_CONF_VARS'] values (namely, those of the Mail API) to be site-specific. After reading Configuration Overview, Site Handling, and GLOBALS - TYPO3_CONF_VARS, I'm still not sure how would it be an idiomatic way to do this.
Also, I'm using helhum/typo3-config-handling for the TYPO3 configuration. The idea is basically having the same functionality that we have with the contexts (i.e having prod.settings.yaml and dev.settings.yaml load different values) but with sites, e.g. I want to have a different $GLOBALS[‘TYPO3_CONF_VARS’]['MAIL']['defaultMailFromAddress'] value wether if I'm in one of my sites or another.
I actually don't know if this is possible to do. Maybe these are thought to be that, just global, and I have to come up with a more ad-hoc solution. E.g. changing the $GLOBALS[‘TYPO3_CONF_VARS’] array beforehand every time some process that accesses it.
Thanks a lot in advance!
You can access Environment variables for domain specific configuration.
Or you use conditions in PHP.
Anyway you need to make your assignments in typo3conf/AdditionalConfiguration.php as all non constant values might get overwritten in typo3conf/LocalConfigurathion.php.
In my previous question I tried to figure out how to identify a computer as accurate as possible. I think the best solution is the usage of Local Shared Objects a.k.a flash cookies. I would like to create a flash object, and two JavaScript or PHP functions to communicate with it. I did a research in the mayor search engines, but I did not found any solution to do that. I only want to store one variable in the object. I have no experience in ActionScripting...
Is there any way to create a local shared object and manipulate it with PHP or JS?
I have an existing .NET application where most of the variables are stored using MemoryMappedFIles.
I am merging this now existing php functionality.
The porblem is now how to access the .NET variables from within php.
My current solution is based on implementing a pipe between both environments, but this does not hold when the load is high. Also, it is difficult to exchange structured data. I could try a relational database or a file in between, but this obviously adds overhead.
Any ideas on how to expose .NET variables into php ?
thanks.
May be its not a good idea. Can you store those memory mapped variable value into cookies and
you can access those value using PHP cookie variable .
eg. $_COOKIE['variable name'];
If variables are going to be used across environments then a shared data store would be a good solution. I do not know too much about .NET variables, and how one might expose them, but it sounds like it might be a bad idea, or at least a hassle.
When sharing data across environments the idea is to think of the data as being stored in one central place:
[.NET] [PHP]
\ /
|
[Data]
This architecture is good because you keep stuff separated, which means that each component can be handled (i.e. optimized and scaled) individually. It also means that you can swap out, or add, components. For example, if you in a month decide to hire a group of Ruby developers to build some project then they will not have to worry about the other languages, they just need to connect to the data store and run with it.
As for what data store to use, it does not have to be files or a relation database; depending on the kind of data, you can use in-memory key/value stores like redis or memcached, or if the data is more structured then maybe a document database like MongoDB would fit better.
I'm still fairly new to PHP and so I'm attempting to understand scope concepts within PHP web applications.
In the Java world a Java web app - using Java Server Pages (JSP) and upward - will allow a Java Bean to have the following levels of scope:
Page
Request
Session
Application
Attempting to map these to PHP's scoping capabilities:
Page: not really but objects that are local to a call are considered 'gone' after the function call is made so it's sort of like a page scope
Request: made by using the "$_REQUEST super global (not sure where this goes ... Cookies? Hidden fields? URL parameters?)
Session: using PHP's $_SESSION super global (where some of the documentation and forum feedback states that this is not a great place to put sensitive information for security reasons)
Application: using PHP's APC (a Stack Overflow link)
Am I totally out to lunch or are these reasonably similar? I know that one major difference is PHP's ["Shared Nothing"][5] architecture as compared to Java's which is to allow for sharing.
Any advice/guidance/sobering corrections most welcome.
You're on the right track. PHP is indeed Share-Nothing.
In a web context, a php application runs, in it's entirety, once for each HTTP request. This means for every HTTP request the interpreter reads, parses and executes the script (this is simplified - using an opcode cache like APC removes the reading/parsing overhead).
PHP feeds input to the script in the form of superglobals, such as $_REQUEST and $_SESSION. Superglobals are different from regular global variables in that they're automatically available in every scope, so there's no need to use the global keyword.
Any data that persist between requests need to be stored externally. To share data across requests to maintain state for a user, you typically use $_SESSION, which by default is serialized and written to files on disk (but can be configured to use a memory cache or database). Data that are to be shared between sessions (which I suppose is similar to the Application scope in the JSP world) need to be stashed somewhere external. You can use a memory cache like APC or memcache, or write flat files to disk, or stick stuff in a database, or use any other scheme you can come up with. At the end of the day, there's nothing built-in.
Aside from superglobals, variable scope is fairly boring. By default, variables live in the scope in which they're created.
To reference a global variable in a non-global scope (ie: inside a function), you need to import the symbol into the local scope using the global keyword. PHP works this way to make it harder to accidentally clobber global variables.
This stuff, and more, is covered pretty well in the manual.
You should probably look at this:
http://php.net/manual/en/language.variables.scope.php
You've got local and global scope, superglobals, static variables. And that page explains how those each work.
I wrote a small PHP application that I'd like to distribute. I'm looking for best practices so that it can be installed on most webhosts with minimal hassle.
Briefly: It's simple tool that lets people download files once they login with a password.
So my questions are:
1) How should I handle configuration values? I'm not using a database, so a configuration file seems appropriate. I know that other php apps (e.g. Wordpress) use defines, but they are global and there is potential that the names will conflict. (Global variables also have the same problem, obviously.) I looked at the "ini" file mechanism built into PHP. It only allows comments at the top - so you can't annotate each setting easily - and you can't validate syntax with "php -f". Other options?
2) How to handle templating? The application needs to pump out a form. Possibly with an error message. (e.g. "Sorry, wrong password.") I've have a class variable with the HTML form, but also allow an external template file to be used instead (specified in the config). I do some trivial search and replace - e.g. %SCRIPT% to the name of the script, %STATUS% to hold the error message. This feels a bit like reinventing the wheel, but including a templating system like Smarty is overkill. (Plus they may already have a templating system.) Other options?
3) i18n - There are only 3 message strings, and gettext doesn't seem to be universally installed. Is it such a bad idea just to make these three strings parameters in the config file?
4) How to best integrate with other frameworks? My app is a single class. So, I thought I could just include a php script that showed how the class was called. It would be a starting point for people who had to integrate it into another framework, but also be fine as-is for those not interested in customizing. Reasonable?
5) GET/POST parameters - Is it bad form for a class to be looking at $_GET and $_POST? Should all values be passed into my class during construction?
Thanks.
Configuration
You can use a php file like this:
<?php
return array(
'option1' => 'foobar',
'option2' => 123,
//and so on...
);
?>
And in the main class just use:
$config = (array) include 'path/to/config/file';
And if you plan to mostly distribute your class as a component in other applications, then simply put config array/object as a parameter in your class' constructor and leave the details to the user.
Templating
For such simple application the method your described should be enough. Remember that one can always extend your class and overload your outputting method with his own.
I10N
As mentioned before, for 3 variables anything more than storing them as config is just overkill.
Integration
Comment each public method (or even better also protected and private ones) with explanations what do they do and what parameters are needed. If you combine that with an example, it should be enough for most users.
GET vs POST
Your class uses passwords and you even think of sending them via GET? ;)
Think of browser history, referer headers etc - your users' passwords would be visible there.
Can config be local to class instances? Or could you create a little class that you could create an instance of to query for config values? Also prepending any global vars with you application's name should go some way to stop clashes.
If your templating is really simple, just write a short templater. It'll be easier than trying to fend off problems people get with any 3rd party templater. It might also simplify licensing issues. If you start worrying about what they already have, you'll never release anything. There are too many combinations.
For 3 strings? Yeah do those the same way you're handling config.
Good comments throughout with an intro explaining how you use the class.
I don't think so. If it bothers you, you could use default arguments to use given arguments first, then search for GET/POST values if none are provided (though that might be a security risk)
There are other things to take into consideration. Lots of people are on shared hosts and as a result, don't have control over their php.ini or their php version. You need to make sure you're only using features that are as commonplace as possible.
One example is that shorttags aren't enabled on some hosts (you have to use <?php ... ?> and <?php echo "..."?> instead of <? ... ?> or <?= "..." ?>) which can be a royal PITA.
In addition to Krzysztof's good advice:
Use <?php only
If you use functions that can be disabled, use function_exists() to ensure they're available. #missing_function() makes PHP die silently without any error logged.
You can't rely on things that can be disabled/changed via php.ini. Use ini_get() to adapt to different settings.
If magic_quotes are enabled, strip slashes only on from your copy of input – don't modify global arrays! Security of some lame code may rely on these slashes being present.
Expect that users will mindlessly copy&paste code from your documentation/website.