I'm having a multiplayer server that's using PHPSockets, and thus is written entirely in PHP.
Currently, whenever I'm making any changes to the PHP server-script I have to kill the script and then start it over again. This means that any users online is disconnected (normally not a problem because there aren't so many at the moment).
Now I am rewriting the server-script to use custom PHP classes and sorten things up a little bit (you don't want to know how nasty it looks today). Today I was thinking: "Shouldn't it be possible to make changes to the php source without having to restart the whole script?".
For example, I'm planning on having a main.php file that is including user.php which contains the class MyUser and game.php which contains the class MyGame. Now let's say that I would like to make a change to user.php and "reload" the server so that the changes to user.php goes into effect, without disconnecting any online users?
I tried to find other questions that answered this, the closest I got is this question: Modifying a running script and having it reload without killing it (php) , which however doesn't seem to solve the disconnection of online users.
UPDATE
My own solutions to this were:
At special occations, include the file external.php, which can access a few variables and use them however it'd like. When doing this, I had to make sure that there were no errors in the code as the whole server would crash if I tried accessing a method that did not exist.
Rewrite the whole thing to Java, which gave me the possibility of adding a plugin system using dynamic class reloading. Works like a charm. Bye bye PHP.
Shouldn't it be possible to make changes to the php source without having to restart the whole script?
[...]
I'm planning on having a main.php file that is including user.php
which contains the class MyUser
In your case, you can't. Classes can only be defined once within a running script. You would need to restart the script to have those classes redefined.
I am not too familiar with PHP but I would assume that a process is created to run the script, in doing so it copies the instructions needed to run the program and begins execution on the CPU, during this, if you were to "update" the instructions, you'd need to kill the process ultimate and restart it. Includes are a fancy way of linking your classes and files together but ultimately the processor will have that information separate from where the file of them are stored and it is ultimately different until you restart the process.
I do not know of any system in which you can create code and actively edit it and see the changes while that code is being run. Most active programs require restart to reload new source code.
Runkit will allow you to add, remove, and redefine methods (among other things) at runtime. While you cannot change the defined properties of a class or its existing instances, it would allow you to change the behavior of those objects.
I don't recommend this as a permanent solution, but it might be useful during development. Eventually you'll want to store the game state to files, a database, Memcache, etc.
How about storing your User object into APC cache while your main script loads from the cache and checks every so often for new opcode.
To include a function in the cache, you must include the SuperClosure Class. An example would be:
if (!apc_exists('area')) {
// simple closure
// calculates area given length and width
$area = new SuperClosure(
function($length, $width) {
return $length * $width;
}
);
apc_store('area', $area);
echo 'Added closure to cache.';
} else {
$func = apc_fetch('area');
echo 'Retrieved closure from cache. ';
echo 'The area of a 6x5 polygon is: ' . $func(6,5);
}
See here for a tutorial on APC.
Simple solution use $MyUser instead of MyUser
require MyUserV1.php;
$MyUser = 'MyUserV1';
$oldUser = new $MyUser('your name');
//Some time after
require MyUserV2.php;
$MyUser = 'MyUserV2';
$newUser = new $MyUser('your name');
Every declared class stay in memory but become unused when the last MyUserV1 logout
you can make them inherit from an abstract class MyUser for using is_a
You cannot include again a file with the same class, but you can do so with an array. You can also convert from array to class, if you really need to do so. This only applies to data, though, not to behavior (methods).
I don't know much about these things with the games on PC but you can try to get all the variables from your database for the user and then update the text fields or buttons using those variables
In web is using AJAX (change data without refreshing the page).Isn't one for programming?
Related
The actual questions
How to "map" access restrictions so it can be used from php and javasript?
What kind of method should I use to share access restrictions / rules between php and javascript?
Explanation
I have created a RESTful backend using php which will use context-aware access control to limit data access and modification. For example, person can modify address information that belongs to him and can view (but not modify) address information of all other persons who are in the same groups. And of course, group admin can modify address details of all the persons in that group.
Now, php side is quite "simple" as that is all just a bunch of checks. Javascript side is also quite "simple" as that as well is just a bunch of checks. The real issue here is how to make those checks come from the same place?
Javascript uses checks to show/hide edit/save buttons.
PHP uses checks to make the actual changes.
and yes,
I know this would be much more simpler situation if I ran javascript (NodeJS or the like) on server, but the backend has already been made and changing ways at this point would cause major setbacks.
Maybe someone has already deviced a method to model access checks in "passive" way, then just use some sort of "compiler" to run the actual checks?
Edit:
Im case it helps to mention, the front-end (js) part is built with AngularJS...
Edit2
This is some pseudo-code to clarify what I think I am searching for, but am not at all certain that this is possible in large scale. On the plus side, all access restrictions would be in single place and easy to amend if needed. On the darkside, I would have to write AccessCheck and canAct functions in both languages, or come up with a way to JIT compile some pseudo code to javascript and php :)
AccessRestrictions = {
Address: {
View: [
OWNER, MEMBER_OF_OWNER_PRIMARY_GROUP
],
Edit: [
OWNER, ADMIN_OF_OWNER_PRIMARY_GROUP
]
}
}
AccessCheck = {
OWNER: function(Owner) {
return Session.Person.Id == Owner.Id;
},
MEMBER_OF_OWNER_PRIMARY_GROUP: function(Owner) {
return Session.Person.inGroup(Owner.PrimaryGroup)
}
}
canAct('Owner', 'Address', 'View') {
var result;
AccessRestrictions.Address.View.map(function(role) {
return AccessCheck[role](Owner);
});
}
First things first.
You can't "run JavaScript on the server" because Javascript is always run on the client, at the same way PHP is always run on the server and never on the client.
Next, here's my idea.
Define a small library of functions you need to perform the checks. This can be as simple as a single function that returns a boolean or whatever format for your permissions. Make sure that the returned value is meaningful for both PHP and Javascript (this means, return JSON strings more often than not)
In your main PHP scripts, include the library when you need to check permissions and use the function(s) you defined to determine if the user is allowed.
Your front-end is the one that requires the most updates: when you need to determine user's permission, fire an AJAX request to your server (you may need to write a new script similar to #2 to handle AJAX requests if your current script isn't flexible enough) which will simply reuse your permissions library. Since the return values are in a format that's easily readable to JavaScript, when you get the response you'll be able to check what to show to the user
There are some solutions to this problem. I assume you store session variables, like the name of the authorized user in the PHP's session. Let's assume all you need to share is the $authenticated_user variable. I assume i'ts just a string, but it can also be an array with permissions etc.
If the $authenticated_user is known before loading the AngularJS app you may prepare a small PHP file whish mimics a JS file like this:
config.js.php:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo "var authenticated_user = '$authenticated_user';";
?>
If you include it in the header of your application it will tell you who is logged in on the server side. The client side will just see this JS code:
var authenticated_user = 'johndoe';
You may also load this file with ajax, or even better JSONP if you wrap it in a function:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo <<<EOD;
function set_authenticated_user() {
window.authenticated_user = '$authenticated_user';
}
EOD;
?>
From what I understand using something like require_once will essentially copy and paste the code from one file into another, as if it was in the first file originally.
Meaning if I was to do something like this it would be valid
foo.php
<?php
require_once("bar.php");
?>
bar.php
<?php
print "Hello World!"
?>
running php foo.php will just output "Hello World!"
Now my question is, if I include require_once inside a method, will the file that is included be loaded when the script is loaded, or only when the method is called?.
And if it is only when the method is called, is there any benefit performance wise. Or would it be the same as if I had kept all the code into one big file.
I'm mainly asking as I've created an API file, which handles a large amount of calls, and I wan't to simplify the file. (I know I can do this just be creating separate classes, but I thought this would be good to know)
(Sorry if this has already been asked, I wasn't sure what to search for)
It will only include when the method is called, but have you looked at autoloading?
1) Only when the method is called.
2) I would imagine there's an intangible benefit to loading on the fly so the PHP interpreter doesn't have to parse extra code if it's not being used.
I usually use the include('bar.php'); i use it for when i use databvase information, i have a file called database.php with login info and when the file loads it calls it right up. I don't need to call up the function. It may not be the most effective and efficient but it works for me. You can also use include_once... include basically does what you want it to, it copies the code essencially..
As others have mentioned, yes, it's included just-in-time.
However, watch out for variable definitions (require()ing from a method will only allow access to local variables in that method's scope).
Keep in mind you can also return values (i.e. strings) from the included file, as well as buffer output with ob_start() etc.
I'm building a service, which has a few cronjobs running, written in Python. However, this is my first Python-project ever, so I'm still a very beginner.
What I'm doing now, is that I have my database-connection handled on every file, so basically if I wanted to change the host, I would need to go through all the files. I'm now looking into a PHP-include() similar method for Python, so that I could include some general stuff instead of copy-pasting.
Also, the Python-files are ran in cronjob, so the method should work on cronjobs too :)
If it's really just a couple of settings for a single database connection, just put it in a Python module and import it in all of your files. Why add any complexity you don't need?
If it's more complicated, use ConfigParser as #AdamMatan suggested.
# dbconfig.py
host = '127.0.0.1'
user = 'stack'
password = 'overflow'
# db.py
import dbconfig
print dbconfig.host
print dbconfig.user
print dbconfig.password
Use an external configuration file, with your db connection (host, name, password, db, ...) in it, and read the configuration file from within the Python script.
This makes changes easy (even for non-programmers) and nicely complies with the Single Choice Principle.
Example:
db.cfg
[db]
host=127.0.0.1
user=stack
password=overflow
db.py
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open('db.cfg'))
print config.get('db', 'host')
Execution result:
127.0.0.1
If you need to call __import__(), you are doing it wrong.
You need to refactor your code so that you no longer have the database connection routines scattered throughout your codebase. Yes, it would be even nicer to have these details in a configuration file (+1 #Adam Matan), but first you need to eliminate the duplication. This will save you a world of pain in the long run.
Heads up: I dont have the possibility to rename the classes or use name spaces for this.
Im looking for any crazy way to subvert class redeclaration issues in php. I actually only need 3 static variables from a web application, but the only way to get them requires including a file that declares a user class. However I already have a user class, so I get an error.
I tried to no avail to include the file in a class hoping it would isolate the included file - But no.
I tried reading an interface file I created that just echos the 3 values, but that actually just reads the php code and not the rendered values.
Is there anything like an opto-isolation system for code?
The only think I can think of is using ajax to do it, but it seems super sketchy. Is there a plain php version of this?
(Was a comment, but got too long.) Doesn't sound doable with your constraints. (You might need to show some code.) -- But if you are asking for a crazy way, and the option to rename the classes just applies to not editing the php script, then:
Load the include file into a variable, then transform it, and finally eval:
$source = file_get_contents("user.php");
$source = str_replace("class user", "class workaround_123", $source);
eval($source); // will give you a workaround_user instead of class conflict
Someone will probably comment on the advisability of eval... But it foremost depends on your code/situation if that's an applicable wacky workaround.
Alternatively you could invoke the user fetching code with a separate PHP process :
exec("QUERY_STRING=user=123 php-cgi user.php");
You could tokenize the whole file and go through it "by hand" to find the values you need.
I am trying to delete some CCK nodes in Drupal using a standalone PHP script while logged in as anonymous user
if(empty($total_deals_for_this_pl)){
$node_nid = $single_result['nid'];
global $user;
$original_user = $user;
$user = user_load(1);
print $node_nid."<br>";
node_delete($node_nid);
$user = $original_user;
}
I am able to retrieve all the nid's successfully but the nodes are not getting deleted. I am loading Drupal as follows
chdir('C:\wamp\www\mysite\platform'); //my drupal resides here
require_once './includes/bootstrap.inc';
include_once './includes/common.inc';
Node_delete() has an access check for delete permissions inside it.
Test again with anonymous users given permission to delete nodes.
Also try adding
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
If that doesn't work you could try up to the session phase:
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
and finally the full dealio:
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
Three options:
Generally, I would recommend using VBO for this kind of thing. Its a more robust solution than a custom script. It's pretty easy to set up and once you've used it you'll probably think of a dozen other ways to use it.
Failing that, make your own module and stick your custom script inside a proper hook. Your custom script on its own might not be playing along with what other modules are expecting.
If you still want to have your own separate script I suspect it's the bootstrap code that's failing. Check out drupal_bootstrap for the options available to you.