PDO sets server response code? - php

I'm making an ajax query to a framework that we use. I am unable to set the server response code except by setting it where the PDO execute method is called.
The pattern works like this:
An ajax query runs, posting to a file, action.php, that validates inputs. If inputs are valid, we call a function in the business logic (application.php), which then calls the underlying PDO insert/save method. If we get a good save, we return TRUE in our action.php function.
In my ajax call, I have a .done() function that confirms the save took place by checking xhr.status. I want to set xhr.status to 201 when we have a successful save, by calling http_response_code(201);. This works if I actually do so in the PDO layer, right after the execute() method, but I can't get it to work anywhere else. Obviously, that is not the right place to set a response code.
Sorry the question is so abstract. Here is a little example of the code that isn't working:
$resInfo = new ResInfo();
if($resInfo = saveResident()){
http_response_code(201);
}
return true;
The response code is not set here. Instead, it is set in the PDO method that saveResident() calls.
Anyone else ever have a similar issue?
EDIT:
I realized that saveResident() returns a copy of the saved object rather than a boolean, so I needed to separate the call to it from persisting the saved object:
if(saveResident()){
$resInfo = saveResident();
http_response_code(201);
}

If you say:
it works within saveResident()
saveResident() runs successfully.
And not right after in that if statement.
I would guess that saveResident returns false, an empty array or nothing at all. $resInfo is not used after all.

Related

what is the difference between return redirect('/') and Redirect::to('/')->send(); function in laravel

First code working. See Below
The second code not working. See Below
Anyone can help provide the documentation for this code Redirect::to('/')->send();
The ->send() method should only be used in places where you cannot return a response directly. And even then, it should be used as few times as possible.
Normally, a request will go through a list of middlewares, end up in a controller which will return a response and exit through another list of middlewares. This is the normal way of returning a response.
When you use the send() function, you interrupt the pipeline and send the response back immediately.
Now, the reason only send() works in your case is because you are redirecting from a constructor and a constructor cannot have a return value. Because of this, the second example will never work.
I would encourage you to use a middleware for this check instead. This way the check is reusable and you can return a redirect response without interrupting the pipeline.

Testing method with no output

I have the following method I want to test:
class SomeObject {
public function actionFromSomeController() {
$obj = new OtherObject();
$obj -> setAttributes();
$obj -> doAction();
}
}
class OtherObject {
private $_attr;
public function setAttributes() {
$this -> _attr = 'something';
Database :: execute('INSERT INTO table VALUES (' . $this -> _attr . ')');
$fileObj = new FileObj();
$content = $fileObj -> getSomeFileContent();
// do something else
}
public function doAction() {
echo $this -> _attr;
}
}
Now I want to test this method, its output depends on database content and one file on the server. It does a lot of things on the way, and the output is just one ID and success => 1.
How should I test it properly?
Some ideas on how to test small code pieces like this:
Generate test-data and pass it to your methods (also, fake database return data or file contents)
Use echo / var_dump() / die() to check property and variable content at different positions in your methods
Also use these commands to check whether execution reaches a certain point (for example to see whether a function got called or not)
If something doesn't work as expected without an error message: Check line by line with the above methods until you find the problem
Consider using interfaces and dependency injection if your code gets bigger - this is a bit over-the-top for this amount of code, but can be a tremendous time-saver when your application becomes big
Testing is never an automatic process and you will always have to think about what makes sense to do and what not. These things to do are never magic but basic PHP.
You should consider letting your scripts throw errors/exceptions if something goes wrong. Writing "silent" applications is almost never good since you can, if you really need a silent execution for production environments, just turn off error reporting and have the same effect. Many PHP functions return something special on failure and/or success and you can check for this. Database handlers do so, too. Do yourself a favor and use these return values!

Writing a subscribe method of RabbitMQ in PHP

I have a function as defined below:
public function subscribe($someQueue)
{
$callback = function($msg){
return $msg->body;
};
$this->channel->basic_consume( $someQueue, '', FALSE, TRUE, FALSE, FALSE, $callback);
while(count($this->channel->callbacks)) {
$this->channel->wait();
}
}
I'm using the following function:
Note: Following lines are in a different class file, hence creating object of the class that contains the above function.
$objRMQ = new RabbitMQ();
$msgBody = $objRMQ->subscribe("someQueue");
echo "message body returned from someMethod: ".$msgBody;
Basically, I want to return body of every message to the caller function that is published to the queue.
Current output:
message body returned from subscribe: NULL
Expected output:
holla, this is your message from queue
Since this question is old but still unanswered, I'll give a brief explanation. You've probably already figured out the answer by now, but this might help someone else searching in future.
The key concept here is "asynchronous execution".
When you subscribe to a channel using the basic_consume method, you are not asking for the callback to be executed once, immediately, but for it to be executed once a message becomes available, and then every time another message is available.
In the case of AMQPLib, you wait for new messages by repeatedly calling the wait() method; i.e. here:
while(count($this->channel->callbacks)) {
$this->channel->wait();
}
Thinking about this carefully, there are two mistakes in your code:
The line return $msg->body has nowhere to return to. The call will happen somewhere deep in the implementation of the wait() method, and you get no output from $this->channel->wait(), so have no way of doing anything with that returned value.
On the other side, when you call $objRMQ->subscribe("someQueue") from your other class, you are expecting it to return something, but that function has no return statement. The only return statement is inside the anonymous function you passed to basic_consume.
The solution is basically to do all your processing of the message - echo $msg->body, or whatever real processing you want to do - inside the callback. If you really want to gather data as messages come in, you could save it to some variable accessible outside the callback, but remember that you will at some point need to break out of the wait() loop in order to do anything with that data.

How to properly call a class while providing error reporting at the class-caller level

I am writing fresh code, as part of refactoring an older legacy codebase.
Specifically, I am writing a Device class that will be used to compute various specifications of a device.
Device class depends on device's model number and particle count and I can call it as $device = new Device($modelNumber, $particleCount);
Problem: since this class will go into existing legacy code, I have no direct influence on if this class will be called properly. For Device to work, it needs to have correct model number and correct particle count. If it does not receive the proper configuration data, internally device will not be initialized, and the class will not work. I think that I need to find a way to let the caller know that there was an error, in case an invalid configuration data was supplied. How do I structure this to be in line with object oriented principles?
Or, alternatively, do I need to concern myself with this? I think there is a principle that if you supply garbage, you get garbage back, aka my class only needs to work properly with proper data. If improper data is supplied, it can bake a cake instead, or do nothing (and possibly fail silently). Well, I am not sure if this principle will be great. I do need something to complain if supplied configuration data is bad.
Here is some code of what I am thinking:
$device = new Device($x, $y);
$device->getData();
The above will fail or produce bad or no data if $x or $y are outside of device specs. I don't know how to handle this failure. I also want to assume that $device is valid when I call getData() method, and I can't make that assumption.
or
$device = new Device($x, $y);
if ($device->isValid())
$device->getData();
else
blow_up("invalid device configuration supplied");
The above is better, but the caller has to now they are to call isValid() function. This also "waters down" my class. It has to do two things: 1) create device, 2) verify device configuration is valid.
I can create a DeviceChecker class that deals with configuration vefication. And maybe that's a solution. It bothers me a little that DeviceChecker will have to contain some part of the logic that is already in Device class.
Questions
what problem am I trying to solve here? Am I actually trying to design an error handling system in addition to my "simple class" issue? I think I probably am... Well, I don't have the luxury of doing this at the moment (legacy code base is huge). Is there anything I can do now that is perhaps localized to the pieces of code I touch? That something is what I am looking for with this question.
I think you need to use below code to verify your passed arguments in construct
class Device {
public function __constructor($modelNumber, $particleCount) {
if(!$this->isValid($modelNumber, $particleCount) {
return false; //or return any error
}
}
}
This will check the passed params are valid or not and create object based on that only, otherwise return false or any error.

Php: Disable debug function in runtime

in php i wrote my own debug function which have two arguments: text and a level of message. However i could be also you the php functions for triggering errors. But to debug in development i use sometimes like this:
debug($xmlobject->asXML(),MY_CONSTANT);
now i want to know whether it is a lack of performance in non debug executing because the arguments are calculated indepent whether they will be used inside function? and how to do that right that is only calculated if i need?
Thanks for your help,
Robert
If you write the following portion of code :
debug($xmlobject->asXML(),MY_CONSTANT);
Then, no matter what the debug() function does, $xmlobject->asXML() will be called and executed.
If you do not want that expression to be evaluated, you must not call it; I see two possible solutions :
Remove the useless-in-production calls to the debug() function, not leaving any debugging code in your source files,
Or make sure they are only executed when needed.
In the second case, a possibility would be to define a constant to configure whether or not you are in debug-mode, and, then, only call debug() when needed :
if (DEBUG) {
debug($xmlobject->asXML(),MY_CONSTANT);
}
Of course, the makes writting debbuging-code a bit harder... and there is a bit of performance-impact (but far smaller than executing the actual code for nothing).
The arguments are sended by value, ergo the method ->asXML() is executed always.

Categories