Couchbase - creating design documents through API - php

I've been using Couchbase for a large project where we only consume data, but have no requrirement to actually write to the Couchbase cluster. I want to write some management tools and be able to create Design Documents and Views through the API and not the web console.
Creating Documents is not an issue at all, but whenever I use setDesignDoc() I get the following error message:
Fatal error: Uncaught exception 'CouchbaseLibcouchbaseException' with message 'Failed to store design doc: Invalid input/arguments' in ....
I can get the actual view data from the source with getDesignDoc() and use it for the creating that design document on the destination server like so:
$connandleDestination->setDesignDoc( "myDesignDoc", $connSource->getDesignDoc("myDesignDoc") );
And that's where I get the above error message.
I'm using the PHP SDK by the way with the latest version against Couchbase 2.5.1

Can you confirm if what you've given as your example is the exact code you're using?
$connandleDestination->setDesignDoc( "myDesignDoc", $connSource->getDesignDoc("myDesignDoc") );
What you've given would not work as, from the API docs, the syntax is as follows:
setDesignDoc(string $name, string $document) : bool
Hence, it would appear you are trying to set a new doc, myDesignDoc to be equal to the design doc myDesignDoc, which would either not exist, or have no effect (as setting something to equal itself causes no change - and creating a new design doc with the name of an existing one will simply overwrite it).
Did you instead mean to just use get()? get() would return a document (which would be valid in the setDesignDoc input, and that document could have the same name as the new design doc to be created.

Related

Adding Raw Query Parameters to SolrQuery requests

I'm using SolrClient with SolrQuery object, but I need to add RawQueryParameters to it:
How is this done? I'm fairly new to Solr requests and I could not find such option in the documentation.
So far I have this:
$SolrQuery = new \SolrQuery();
$SolrQuery->setStart($this->offset);
$SolrQuery->setRows($this->limit);
$SolrQuery->setQuery($request);
$SolrQuery->addField('*')->addField('units:[subquery]');
$SolrQuery->addParam('units.q', '{!terms%20f=id%20v=$row.unit_ids}');
When running toString() on this object, I get:
start=0&rows=2147483647&q=type:address&fl=*,units:[subquery]&units.q={!terms%20f=id%20v=$row.unit_ids}
what is the correct query. This works fine in CLI, but gives exception when executed in PHP as $queryResponse = $SolrClient->query($SolrQuery);:
Exception: while invoking units:[subquery] on doc=SolrDocument{id=stored,indexed,tokenized,omitNorms,indexOptions=DOCS
EDIT: Solution was to use addParam() without urlcoded request. Spaces go through just fine!
You can get the active parameters by calling ->toString() on the SolrQuery object - since SolrQuery inherits from SolrModifiableParams, you can call addParam directly on the query object to add custom parameters. This lets you add any parameter you want to the request. Be careful to add the parameter verbatim, since SolrQuery should handle necessary escaping for you.
If you still see an error, you can check the logging on the Solr server (under Admin -> Logging). If the log level is set to INFO, Solr will log all requests so you can see what Solr actually got. Any exceptions should also be present in this log if they're generated on the Solr side.
The Solr extension will usually throw exceptions as the class SolrClientException, which can be useful to determine the source of the error. A list of exception messages are also available in the extension source if you need to debug further.

Apigility "Error saving field" while creating "db-connected" service

When I try to create a new service using db-connected in Apigility, I'm getting the error Error saving field. After receive the error, the service is created but if I select this one, I receive the error Unable to fetch service.
It seems to happen always when I create a db-connected service in a table with name containing "_".
The error that I'm getting in console is:
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (Hookit-V1-Rest-Vitrine_usuario-Controller, line 0)
I checked the module's config and the parameters are have been created.
in module's config in node zf-apigility O removed the parameter resource_class and the run the service... It worked.
but I can't sync the service in admin.
Does someone knows how to solve it to sync the service in Apigility's admin?
Alessandro Garcez is correct. This issue was resolved in this merge https://github.com/zfcampus/zf-apigility-admin-ui/pull/59
However, this merge has been overwritten and in the latest version, you will get the same issue. I have made a pull request to bring back the fix that Alessandro Garcez mentioned.
It seems that when the new service is created, if the table name contains an underscore ( _ ), the API will convert this to what looks like CamelCase.
But when the UI then wants to create the fields for this newly created service, it (the UI) will still use the tablename with the underscore in it, when accessing the api (/apigility/api/module//rest/--Rest--Controller/input-filter)
But the API will this time expect the controller-part being specified with the tablename camedcased:
(/apigility/api/module//rest/--Rest--Controller/input-filter)
It had already been fixed but was undone, I don't know why.
There is a opened discussion https://github.com/zfcampus/zf-apigility-admin-ui/issues/78.
For now is possible follow this way:
Change the function capitalizeFirstLetter in file src/apigility-ui/service/api.service.js adding the line var string = string.replace(/(\w)/g, function(,letter) { return letter.toUpperCase(); }); before the return.

Error when Querying Parse with PHP

I am trying to use the Parse.com SDK with PHP. I have downloaded and installed the SDK and I have successfully created a test object.
However, when trying to retrieve an object with a basic query using the sample code provided in the Parse docs and when I try to run it I get:
Fatal Error: Class 'ParseQuery' not found in /home/jameshilton/public_html/index.php on line 109
I would have guessed that it is not linking to the SDK properly but everything else is working fine.
Any ideas what I'm doing wrong?
By looking at the code of the class ParseClient in on GitHub I can see that the classes are declared in the namespace parse. So when you need an object from the Parse library you need to select the namespace. This can be done in two ways.
At the top of your file write:
use \parse;
or when instantiating the class:
$query = new \parse\ParseQuery
And remember to make sure the files are included either through an autoloader (composer?) or manually using include or require.
Regards.

XSD schema based XML validation in PHP unit test

I am developing a PHP-powered application component which exports some data to an XML file which must follow a scheme defined by XSD file. I know how to validate the file manually, but it would be very handy if this could be done within unit tests.
Is there any library or framework available which can me help doing that?
One possibility would be to use DOMDocument::schemaValidate or DOMDocument::schemaValidateSource. Since either of those two methods returns a boolean value, you could then assert that the returned value is true.
This PHPUnit XSD validation lib defines a custom PHPUnit_Framework_Constraint uses DOMDocument::schemaValidate.
The advantage is that it gives a useful error when the validation fails, rather than just saying that 'false is not true'.
Usage
$constraint = new Jasny\PHPUnit\Constraint\XSDValidation("myschema.xsd");
$xml = $this->object->doSomething();
$this->assertThat($xml, $constraint);
Note: This is a shameless plug of my own open source library.

How to design error reporting in PHP

How should I write error reporting modules in PHP?
Say, I want to write a function in PHP: 'bool isDuplicateEmail($email)'.
In that function, I want to check if the $email is already present in the database.
It will return 'true', if exists. Else 'false'.
Now, the query execution can also fail, In that time I want to report 'Internal Error' to the user.
The function should not die with typical mysql error: die(mysql_error(). My web app has two interfaces: browser and email(You can perform certain actions by sending an email).
In both cases it should report error in good aesthetic.
Do I really have to use exception handling for this?
Can anyone point me to some good PHP project where I can learn how to design robust PHP web-app?
In my PHP projects, I have tried several different tacts. I've come to the following solution which seems to work well for me:
First, any major PHP application I write has some sort of central singleton that manages application-level data and behaviors. The "Application" object. I mention that here because I use this object to collect generated feedback from every other module. The rendering module can query the application object for the feedback it deems should be displayed to the user.
On a lower-level, every class is derived from some base class that contains error management methods. For example an "AddError(code,string,global)" and "GetErrors()" and "ClearErrors". The "AddError" method does two things: stores a local copy of that error in an instance-specific array for that object and (optionally) notifies the application object of this error ("global" is a boolean) which then stores that error for future use in rendering.
So now here's how it works in practice:
Note that 'Object' defines the following methods: AddError ClearErrors GetErrorCodes GetErrorsAsStrings GetErrorCount and maybe HasError for convenience
// $GLOBALS['app'] = new Application();
class MyObject extends Object
{
/**
* #return bool Returns false if failed
*/
public function DoThing()
{
$this->ClearErrors();
if ([something succeeded])
{
return true;
}
else
{
$this->AddError(ERR_OP_FAILED,"Thing could not be done");
return false;
}
}
}
$ob = new MyObject();
if ($ob->DoThing())
{
echo 'Success.';
}
else
{
// Right now, i may not really care *why* it didn't work (the user
// may want to know about the problem, though (see below).
$ob->TrySomethingElse();
}
// ...LATER ON IN THE RENDERING MODULE
echo implode('<br/>',$GLOBALS['app']->GetErrorsAsStrings());
The reason I like this is because:
I hate exceptions because I personally believe they make code more convoluted that it needs to be
Sometimes you just need to know that a function succeeded or failed and not exactly what went wrong
A lot of times you don't need a specific error code but you need a specific error string and you don't want to create an error code for every single possible error condition. Sometimes you really just want to use an "opfailed" code but go into some detail for the user's sake in the string itself. This allows for that flexibility
Having two error collection locations (the local level for use by the calling algorithm and global level for use by rendering modules for telling the user about them) has really worked for me to give each functional area exactly what it needs to get things done.
Using MVC, i always use some sort of default error/exception handler, where actions with exceptions (and no own error-/exceptionhandling) will be caught.
There you could decide to answer via email or browser-response, and it will always have the same look :)
I'd use a framework like Zend Framework that has a thorough exception handling mechanism built all through it.
Look into exception handling and error handling in the php manual. Also read the comments at the bottom, very useful.
There's aslo a method explained in those page how to convert PHP errors into exceptions, so you only deal with exceptions (for the most part).

Categories