PHP Validating a lot of fields on obj instantiation - php

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

Related

Parse PHP SDK - Create new object whilst also creating relation object

I'm currently saving an object into a class in Parse which currently works fine.
Up to now this has mostly been flat data or the odd pointer which i'm comfortable with.
However, I've recently created a relation column is linked to a Child class which consists of a String and 2 pointers. This data will be provided at the same time as the main row is created.
In theory:
Post data from form to php to process - before saving the main object, create a new ParseObject for the relation providing the String data and associativeArray pointer id's.
Is this the correct way to do it? I have a strange feeling that i will need to save the main row before adding the relation?
Any help would be appreciated greatly :)
You will need to save the main row before adding the relation, because the relation relies on a reference, which relies on an objectId, which doesn't exist until after the initial save. I'm unfamiliar with PHP, though would recommend you add this relation in the success handler of the save call, if there's an equivalent. If there isn't an equivalent, it may be better to write a cloud code function in js to do this, so you can utilize promises / callbacks, and pass the data you have to that function instead of saving the object on your PHP client.

Subsets of properties in a Swagger definition

I'm writing an API where I have a Controller that POSTs a new object, GETs it back and can PUT/PATCH updates to it. The problem is that there's a difference in properties between the two different actions. For example, when I POST a new object I want to ensure that the 'id' of it is returned so that it can be used to identify it for the GET/PUT/PATCH endpoints. It doesn't matter if it comes back via the GET (it's just a duplication of data at that point) but I certainly don't want it passed for the PUT or PATCH as the id is immutable.
So what's the best way to mark this up in swagger so that I can have different versions of the same Definition? I've seen that you can use 'allOf' to add Definitions to other properties, but I'm wondering if there's a way of saying 'not these properties in the definition'?
If I could do the latter I could make one Definition of the object as a whole and simply knock out the things that aren't required to be returned or submitted when referencing it at the Controller. Is this possible? Am I making sense?
(Just to make things more interesting, my swagger.json file is being generated by swagger-php based on Annotations in my controller and entity files)
I am facing the same issue while writing our spec file, and didn't know how to fix it but what I used is the property "readOnly":true, this way the documentation says that this is a readonly property, you can only read it through GET/POST methods but you cannot send it via PATCH/ PUT.. hope this helps

Better to pass complete object or just a required value in PHP (Symfony 2)?

I would like to ask if it's better to pass a complete array or object to view or just a required value?
For example, controller is rendering some view which needs 2 parameters:
client.id and client.name
and now, will it have a big impact on the speed performance if I will pass complete client object (can have lots of data) or not at all?
When You passing an object in reality you pass reference to it and it has 32bits size.
So if You alredy have object crated and You just need to pass some of its values to view better to pass its reference instead of only required values, You will crate just one new variable instead of x.
#Gustek it's right, but arrays works by reference too.
I made some test with kohana codebench a few years ago, and process data is more efficient in arrays than objects.
A good coder would pass required values only...

API Design: Multiple $_REQUEST's vs single $_REQUEST encoded in json

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.

ideas for simple objects for day to day web-dev use?

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.

Categories