I'm building an API, and I'm at a crossroads as how to implement it. I plan on using json, since they can represent objects/arrays so easily in php and javascript.
I have two ways to implement it pretty much:
1) Include the method call into the json
$input = $_REQUEST['i'];
$i_obj = json_decode($input);
api_handle($i_obj);
2) Push the method call (and perhaps other variables, such as the session) in parallel, and just pull the data via $_REQUEST.
$method = $_REQUEST['m'];
$argv = json_decode($_REQUEST['argv']);
api_handle($method,$argv);
I can see that in the second case, there may be less for the json_decode to debug, but from a user friendly point of view, an ajax/js coder could just build the object and send it json_encoded via input "i".
My question in the end is, are either of these good ways to implement this, or is there perhaps an even better way? Please keep in mind, this is a simple example, and does not represent the rest of the project's scope for this API.
In this particular case it's better idea to couple all method call data into one object rather then getting it from $_REQUEST key by key since $_REQUEST contains other unrelated data as well at the same level.
Method name and its arguments are tied together and must be transferred as single packet. Maybe some day you'll deside to add ability to call i.e. class static methods. It will be much harder to add one more key to $_REQUEST and its processing then add one more field to object since object is much more encapsulated thing and that will narrow area affected by changes in your code.
And of course you can name object fields by a whim withot thinking if this key is already taken in $_REQUEST by another script.
Related
I have a class that represents data returned from a RESTful API. The data returned may contain a lot of different fields or arrays that I want to represent with my object. There may be something like 20 different fields I may have to initialize when the object is created. Some of those fields may be empty depending on the ID I'm trying to get back. I need to do some basic validation to make sure I'm only initializing the fields for values that exist. A simple null/empty check should suffice for this but I don't want a lot of repeated code.
Is there any way to easily accomplish this with magic methods or do I need to manually validate everything with a helper method of some sort?
a couple mouth ago I was worked on a Rest JSON API Wrapper.
Array with loop
My first Idea was to put all my field in a array and validate it with a loop to check the data integrity,
but really specific field like only three string value possible, or one integer with 3 possible value, this method is not enough.
Specific container
So I build specific object container with a specific test in all my field in my object constructor.
The code seams to be very heavy but really simple and obvious if you make if condition one by one (not in cascade).
You can avoid mistype issue or copy past bugs with unit test, and cancel the construction of the object if something is missing or wrong.
JSON Validation
I assume you use json or xml to exchange data between your code and the REST API,
seam to be obvious but JSON validation first give a good idea if you get all your information.
Hope it's help
Regards
I've inherited some PHP code that I need to make significant changes on. I know with PHP it is possible to serialize an Object, and pass the serialized text between pages as FormData. In the code I've inherited, they have done just that, But this is creating some maintainability problems. I'm wondering if taking this approach is even a good idea.
For example ...
When the user opens PageA.php the following is created:
$expensiveObj = new ExpensiveClass($id);
The $expensiveObj is then serialized and the resulting text is stored in a div with the following:
<div id="expensiveObj"><?php echo strtr(base64_encode(serialize($expensiveObj)), '+/=', '-_,');?></div>
When PageA.php loads, an ajax call is made to PageB.php. The content of the div is passed along as a post variable to PageB.php. Within PageB.php the following code unserializes the object:
$expensiveObj = unserialize(base64_decode(strtr($_POST['expensiveObj'], '-_,', '+/=')));
The fields and methods of the $expensiveObj are now accessible to PHP. The problems I'm encountering are
Because the $expensiveObj is not identified in PageB.php as an instance of the Class ExpensiveClass then the IDE doesn't know that the fields and functions of ExpensiveClass are available. I can't do autocomplete, nor lookup within the IDE what functions are available. Plus the IDE can't catch potential issues. The other developer worked exclusively in VI, so he never cared.
PageB.php needs to be re-factored. There is view, business, and controller logic all happening within this page, I would prefer to create a couple of classes, but I'm encountering a problem where I don't know how to pass the $expensiveObj to a class.
My questions are, is there a way to pass an Object to a class? And is there a way inform the IDE that the passed in post variable is indeed an instance of ExpensiveClass?
Lastly, is it even a good idea to be passing around objects this way, or should I be looking at a larger re-factor?
Storing objects directly in HTML is never a good idea, because it can be easily changed by client. In PHP is more common to create new object on every request according to given parameters. I see you are initializing your object using $id, so you can just pass this id between requests. Storing data to session also isn't best practice, session should be used for session-specific data, e.g. logged-in user etc.
If the creation of the object is very expensive, you can use cache, e.g. memcache, some external library or just to write your own, for example storing data in JSON on file system or in database.
I am required to build a complex control panel.
It has to be user configured and after he has made an arbitrary number of changes, he submits them and is presented with the newly configured report.
Now there are a lot of possible configuration options and the JS must be able to draw the control elements/init them with values and PHP must do the business logic - all based on given configuration object - and both must be able to change the values of options before passing the object to the other side.
Now the obvious solution is to have predefined configuration objects on both sides:
PHP:
class config {
public $anArray = array();
}
JS:
{
anArray : []
}
And the sides can communicate fluently via json_encode and $.parseJSON.
However, the structure of both entities must match and I've no idea how to ensure that. Has anyone any ideas on how to communicate complex data structures among those two technologies?
EDIT: to clarify, by structure I mean the properties of the two objects: the object itself is a simple configuration wrapper so it has no private properties, no methods etc, only public fields that are scalar or simple indexed arrays.
So I want a solution to develop it in a DRY way: if I want to add a field called for example "paginationEnabled" it should appear in both - the JS and PHP object:
PHP:
class config {
public $anArray = array();
public $paginationEnabled = true;
}
JS:
{
anArray : [],
paginationEnabled : true
}
I could implement them separately on both sides, but it would not be DRY (which is terrible in this scenario) and I can sense there must be a solution for that, I just can't think of one.
The simplest solution is to included the entire JSON-encoded object structure on every request to the server, and in every page returned by the server. This will be necessary anyway since neither PHP nor JavaScript persists between page loads (unless you're using AJAX, which would only make the JavaScript persist anyway).
Of course that only works if the data is already in a form that can be JSON-encoded. (Arrays and simple objects can be encoded to any depth, but not objects of nontrivial classes, file handles or functions.) If it isn't, then you'll need to convert it to one, then convert back on the other end - for example, if the class of an object is important, then you first need to ensure that a corresponding class exists on the other side, then you can indicate the desired classname with {class: $class, value: $value} - and add code on the other end to find that construction and rebuild an object of the desired class. If you need to copy functions across, then that might be manageable if you store all of your functions as JavaScript, and include a JavaScript interpreter library in PHP. That's probably more trouble than it's worth, however.
If the JSON object is much too large to send on every request, then you're left with storing it in the database (in a form suitable for databases) and using AJAX to update the database when something changes on the JavaScript side, or to retrieve any part of the object that the client code doesn't already have.
Dang-I know this is a subjective question so will probably get booted off/locked, but I'll try anyway, because I don't know where else to ask (feel free to point me to a better place to ask this!)
I'm just wrapping my head around oop with PHP, but I'm still not using frameworks or anything.
I'd like to create several small simple objects that I could use in my own websites to better get a feel for them.
Can anyone recommend a list or a resource that could point me to say 10 day-to-day objects that people would use in basic websites?
The reason I'm asking is because I'm confusing myself a bit. For example, I was thinking of a "database connection" object, but then I'm just thinking that is just a function, and not really an "object"??
So the question is:
What are some examples of objects used in basic PHP websites (not including "shopping cart" type websites)
Thanks!
Here's a few basic reusable objects you might have:
Session (identified by a cookie, stored server side)
User (username, password, etc.)
DBConnection (yes, this can be an object)
Comment (allow users to comment on things)
It sounds like you want to start to build your own web framework, which is a decent way to learn. Don't reinvent the wheel though. For a production site, you're probably better off using an existing framework.
Since you said you don't want to glue HTML and CSS again, you don't try this:
Create a WebForm class. This class is a container of form elements. It has methods to add and remove form elements. It has a getHTML() method that writes the form so that the user can input data. The same object is when a POST is made. It has a method to validate the input of the user; it delegates the validation to every form element and then does some kind of global validation. It has a process method that processes the form. It is final and checks whether validation has passed. If it passed it calls an abstract protected method that actually does the form-specific processing (e.g. insert rows into the DB). The form may be stored in the stored in session, or it may be re-built everytime (if it is stored in the session, it's easier to make multi-page forms).
Create a BaseFormElement and then several child classes like EmailElement, PhoneElement etc. These have also a getHTML() method that is called by WebForm::getHTML() and that prints the specific element. They have a validate() method that is called by WebForm::validate() and a getData() method that returns the properly validated and processed data of that element.
These are just some ideas. Some things may not make sense :p
I'd say database access would be the first most likely object - encapsulate your most common SQL requests into one class. If you make them abstract enough, you can use them for a wide variety of data access situations.
The way to think about class design/usage is to think of the class responsibility. You should be able to describe the class purpose in a short sentence (shorter than this...) i.e for database access object, you might say:
"provides API for common data access tasks"
If any of the methods in your data access class do something other than that, then you know they belong somewhere else.
Is it considered 'bad practice' to create an function like so:
// $arr_member_fields['first_name'] = $_POST['first_name'];
// $arr_member_fields['last_name'] = $_POST['first_name'];
// $arr_member_fields['email'] = $_POST['email'];
// $arr_member_fields['dob'] = $_POST['dob'];
// $arr_member_fields['gender'] = $_POST['gender'];
function update_member($int_member_id $arr_member_fields)
{
//some code
}
Or should a create a function with no array and just use variables instead -- like so:
function update_member($int_member_id, $str_first_name, $str_last_name, str_email, $str_dob, $chr_gender)
{
//some code
}
The reason why I prefer the first method (the one with the array) is that I always have the option to loop through the array for database insertion/updating purposes.
Very curious to know other peoples inputs on this.
Depends on the function. There is no best practice here that will adequately capture most cases when writing a function. What if you don't need to loop through the arguments?
Seems like you're best off passing arrays in this case.
This is a case where I would consider a structure to hold the data. That way I can pass the structure or an array of structure to a methods or I can access individual elements of the structure.
Of course if I wanted to go further I'd made a class instead of a structure. Then I can have methods as well as data, setters, getters with validation, and so on.
Things like this ultimately come down to effects on performance and code readability. While passing an array is extremely handy, it also makes it difficult to follow for someone else reading your code (or even for you if you're coming back to it 6 months later). This is especially true if the array is defined somewhere else in a large file, or another file altogether.
At the end of the day it really comes down to why you're trying to optimize your code in the first place. Is it for performance, or to make it easier to understand/read?
If it's for readability, pick the approach that seems easiest to understand. You'll thank yourself when you have to go back and tweak something months from now.
If it's for performance, make sure you actually need to improve performance and that you aren't optimizing something just for the sake of optimization. More often than not, you'll create a very real readability problem in an effort to solve a nonexistent performance problem.
I would go with the second method because your IDE can tell you what parameters it should take without having to go to that file. It might seem ok to use an array now for a small project, but as your project becomes larger its likely to become a problem later. It will also save you from asking yourself later when you're trying to use it "Did I use name_ first, or first_ name?" Those fields look like something that would all be in one table, which would be updated in a single statement anyway, so I don't see any reason you would want to loop over the array.
I think that passing parameters by array is generally a bad idea. If parameter lists are so long that they justify being passed as an array it's probably a sign that the code is not designed in the best way.
Passing parameters in an array is more difficult to document using something like PHPDocumentor and will also not be picked up by the code-completion in an IDE. Passing parameters explicity also allows for type hinting and is more transparent to the reader of the code.
Obviously if you are passing an array of items to be processed as a function argument then it makes sense to pass it as an array.