Menu
  • HOME
  • TAGS

ZF2 JSON-RPC - Error response, data parameter, how to access?

Tag: zend-framework,zend-framework2,json-rpc

Let's say I have an RPC call for adding colors. A user can only add colors once. If they add one a second time, I want to return an error response that tells them they screwed up, and why.

The JSON-RPC error response describes an error object that includes a space for a data parameter. It is in here that it seems appropriate to include my error code for "color already added". However, I cannot figure out how to return this in the response.

$jsonRpc = new Server();
$jsonRpc->setClass(new Testi());
$jsonRpc->getRequest()->setVersion(Server::VERSION_2);

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    echo $jsonRpc->getServiceMap()->setEnvelope(Smd::ENV_JSONRPC_2);
}
else {
    $jsonRpc->handle();
}


class Testi {

    const ERROR_CODE_COLOR_EXISTS = 5;

    private $colors = ['red', 'green'];

    /**
     * @param $color
     * @return array
     */
    public function addColor($color) {
        if (in_array($color, $this->colors)) {
            throw new \Exception('Color exists');
        }
        else {
            $this->colors[] = $color;
        }

        return $this->colors;
    }
}

This works, to the degree that an error response is returned, but gives me no option to include my error code (self::ERROR_CODE_COLOR_EXISTS).

{"error":{"code":-32000,"message":"Color exists","data":{}},"id":"","jsonrpc":"2.0"}

How do I put info into that DATA parameter!?

Thanks, Adam

Best How To :

Turns out you have two choices to do this:

1) Add parameters to an exception:

$e = new Exception('I pooped my pants');
$e->color = 'brown';
$->smell = 'bad';

color and smell would then be in the data parameter of the error response.

2) Pass the server (in my code, $jsonRpc) into the object (in my code, it would look something like: new Testi($jsonRpc)), and use the fault(...) method, which allows you to pass the data array/object into it.

The latter approach gives you more flexibility as you can do data->code, data->message, neither of which can you set on the $e object, because they are existing, protected parameters. But you are then coupling your model to the $jsonRpc server, which is not good.

All that being said, it's not the correct way to respond to the scenario I outlined above. The error response is more or less reserved for true, unrecoverable server errors, akin to real exceptions, not user validation errors. In my case it was better to define a response type that allows me to return success/fail values with appropriate response codes. {success: false, code: 5}.

Cheers, Adam

how retrieve array returned by config in zend framework 2

zend-framework2

This config is merged automatically in the whole app config. You can get this by calling $sl->get('config') on your ServiceManager. There will be all the config you have....

zend2 forms and action attribute

forms,zend-framework2

The first parameter of the URL helper should be the name of the route you want to use, not NULL. By using NULL, ZF will fall back on using the current route, which I'd guess is not correct in your case.

ZF2 Bulk insert using INSERT INTO … SELECT from a table to same table

php,zend-framework2,bulkinsert,insert-into

There is no method for bulk insert in ZF (Zend\Db), so you have to write a method for that. Zend\Db\Sql\Sql multiple batch inserts The bulk insert is supported in MySQL but not in all databases... Check discussion on link. You can execute raw SQL query for this case: $parameters =...

PHP Frameworks and Project Repositories

php,git,github,zend-framework2,repository

Use Composer: Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you. Install Composer Run composer require 'zendframework/zendframework:2.5.1' This will create or update your composer.json and composer.lock files These files...

zend2 adding another controller to application

controller,routing,zend-framework2

You can have multiple controllers in a single module, but you need to set up your routing to identify when to use which controller. Since you have referenced Akrabat's album module in your question, I'll use it to illustrate: The album module tutorial shows how to create four actions: indexAction,...

Zend Framework 2 routing error: resolves to invalid controller class or alias

zend-framework,routing,zend-framework2,zend-framework-mvc,zend-framework-routing

At the moment the route named application (the parent) defines a URL route of /application. The child route default however requires the controller name to be passed in as the first argument, followed by action. This means the URL would be /application/[:controller]/[:action] So visting /application/test You are inadvertently trying to...

CORS POST request in ZF2 becomes OPTIONS request instead

php,zend-framework2,cors

So to start with your php script should do these checks: // Allow from any origin if (isset($_SERVER['HTTP_ORIGIN'])) { header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 86400'); // cache for 1 day } // Access-Control headers are received during OPTIONS requests if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) header("Access-Control-Allow-Methods: GET, POST, OPTIONS");...

PHPUnit: Testing RestFul API with die response

php,json,api,zend-framework2,phpunit

I would strongly suggest trying to find the solution in rewriting your the code that returns your JSON string inside your controller. Using die to return a response object is not the way to go. An example on how to return JSON from your controller action could be as simple...

ZF2 & Apigility - Correct way to setup GET and POST RPC services

zend-framework2,apigility

In general you POST your new entities on the collection endpoint so in your case /api/verify/merchant. The server will respond with a new resource with a self href for the newly created Merchant. This href will be formatted like /api/verify/merchant[/merchant_code] where merchant_code will be the identifier for the newly added...

Expecting Zend to fail to find an action, but instead it finds it and tries to render a view

php,routes,zend-framework2

Interesting problem. By default ZF will render templates based on the action name, but it uses hyphenation for template names as a convention, and will convert camel-cased actions into this format. PHP functions are not case sensitive, so in your example, checkImageSAction() is what gets called, and so check-image-s.phtml is...

Transfert a Zend Project to Symfony

php,symfony2,zend-framework

There is no way* I can think of that would allow you to automatically transfer a project from Zend Framework 1 to Symfony2. You would have to start all over again, from scratch. My boss made me do that, there was this app written in C, Python, Perl, Bash and...

Best way to configure a Table in Module.php - Zend 2

php,zend-framework2

In short what you've done is fine but I would argue that it isn't best practice. Configuring services in module.php isn't the best habit to get into, it becomes very messy very quickly as you've discovered. A better direction is to use more features of ZF2 to help your predicament....

Create a subquery using ALL and ANY statements

mysql,zend-framework2,any

Why don't you use join tables? select * from distrinct as d join address as a using(districtId) join schedule as s on s.addressId=a.addressId and s.workshopId = '1'; regards...

Failed installation of zend-escaper with Composer

php,zend-framework,composer-php

The PHP version on the command line can be a different executable than the PHP running inside the web server. It also can use a different pho.ini configuration file. So if Composer states the PHP it is using is 5.3.5, this is correct because Composer is directly asking the PHP...

Zend_Pdf how to reduce the loading time of images?

zend-framework,zend-pdf

If your images contain transparent backgrounds, they will take a long time to render in Zend_Pdf. Try removing the transparent backgrounds (if possible) and see if that makes a difference. If that helps, you could use GD library or ImageMagick to replace transaparent backgrounds with white backgrounds as the logos...

zend framework 2 controller's action arguments

zend-framework2

Grab it from params controller plugin. public function indexAction() { $bar = $this->params()->fromQuery('bar'); return new ViewModel(); } ...

zend framework 2 nested module structrue in one main module

php,zend-framework,zend-framework2

Your autoloader probably can't find your controller because it's under a different namespace. Try specifying the Login namespace and see if it helps. 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, 'Login' => __DIR__ . '/src/Login', ), ), ...

Validator EmailAddress can validate an array of email

php,validation,email,zend-framework2,jquery-select2

Why are you not embracing OOP? Create new validator for this: namespace YourApp\Validator; use Zend\Validator\EmailAddress; class EmailAddressList extends EmailAddress { public function isValid($value) { $emails = array_map('trim', explode(',', $value)); foreach ($emails as $email) { if (!parent::isValid($email)) { return false; } } return true; } } and in your validator spec:...

zf2 call a method from a Model in another Model

model-view-controller,zend-framework2

This should be fairly simple. Firstly you need to include the two modules in your application.config.php 'modules' => array( 'Module1', 'Module2' ) Then as a very basic example taken from your question: <?php namespace Module2\Model; use Module1\Model\Class1; class Class2 { public function doSomething() { $class1 = new Class1(); $class1->doSomething(); }...

Zend 2 Navigation add before label name

php,zend-framework2

You have to set a new template for your Zend_Navigation, Add an icon information in your array, 'navigation' => array( 'default' => array( array( 'label' => 'Users', 'icon' => 'gi gi-user', 'route' => 'user_list', 'pages' => array( array( 'label' => 'add user', 'route' => 'user_add', ), ), ), Create a...

Zend Framework 2 - Accessing 2 different tables from same controller file

php,mysql,module,zend-framework2,tablegateway

According to manual Create model Create model table Add factory to your module return array( 'factories' => array( 'Album\Model\ArtistTable' => function($sm) { $tableGateway = $sm->get('ArtistTableGateway'); $table = new ArtistTable($tableGateway); return $table; }, 'ArtistTableGateway' => function ($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new ResultSet(); $resultSetPrototype->setArrayObjectPrototype(new Artist()); return new TableGateway('artist', $dbAdapter,...

Zend paginator with AJAX

jquery,ajax,zend-framework,pagination

It depends how your front-end is built but you are on the right track. Zend1 provided a nice helper called a context switch that does most of the work for you (disables view, sets appropriate headers) but it's not necessary to use it. The general idea is to keep that...

Zend Framework 2: Create Search Widget for Layout

php,zend-framework2

The AbstractHelper has a getView() which returns the 'renderer'. This means you can use all the view helpers you need, as if you were in a view script. The new helper could look like this. use Zend\Form\ElementInterface; class DisplaySearchForm extends AbstractHelper { protected $element; // Form element to render public...

Pass array on url using zend framework 2 routes

php,zend-framework,routes,zend-framework2

Since I had no feedback I had to make a workaround. Here's how I managed to accomplish what I asked: First, instead of using: www.example.com/Search/Attribute1-X-Attribute3-Y/Search/Attribute2-Z I used something like this: www.example.com/Search/Attribute1/X/Attribute3/Y/Search/Attribute2/Z I first used a regex to this route on my module.config: 'search' => array( 'type' => 'Application\Router\SearchesImprovedRegex', 'options' =>...

integrate login to my sites with OpenId or OAuth

login,zend-framework2,oauth-2.0,openid,integrated

Clicking the Google button on the Stackoverflow login screen secretly fills the URL https://www.google.com/accounts/o8/id as OpenID URL. This is an XRDS file which tells the OpenID library where the auth server can be found. The OpenID spec defines this in section 7.3.1: If the end user entered an OP Identifier,...

ZF 2 - Fatal Error: Call to a member function getPosts() on null

php,zend-framework2,fatal-error,member-function

You have registered the controller as an 'invokable'. When the the controller manager creates IndexController it will do so without using the IndexControllerFactory; therefore the Rxe\Factory\PostsTable dependency is never set. To fix this, update module.config.php and register the index controller with your factory class. 'controllers' => [ 'factories' => [...

Zend 2 Translation global

php,zend-framework2

Set translator in your module config as in Zend Skeleton Application

How to send field name for required true validation in zend

php,zend-framework,zend-form,zend-validate

Try this:- $this->addElement( 'text', 'title', array( 'placeholder' => 'Title', 'class' => 'form-control', 'required' => true, 'filters' => array( 'StringTrim' ), 'autocomplete' => 'off', 'validators' => array( array('NotEmpty', false, array('messages' => array(Zend_Validate_NotEmpty::IS_EMPTY => 'Title is required and cant be empty'))) ) ) ); ...

Uninstalling php 5.3 in ubuntu 14.04

php,zend-framework,ubuntu-14.04

The below answer credit goes to Maythux To uninstall something you installed from source, you would use cd back into the directory you built it from and then run sudo make uninstall but I don't think this will work with PHP since it doesn't have an uninstall. So what you...

The class 'Doctrine\ORM\EntityManager' was not found in the chain configured namespaces XXX

php,doctrine2,zend-framework2,doctrine

The error you are getting relates to Doctrine not being able to find an Entity called Doctrine\ORM\EntityManager, which is clearly wrong. My guess is that somewhere (perhaps in the getEntityManager() method) you are passing an instance of the entity manager to the entity manager. For example $entityManager = new EntityManager();...

Zend Framework 2 - Sending form using Zend\Mail

php,jquery,ajax,zend-framework,sendmail

While I was implementing my email method I was never able to get the exception with: catch (\Exception $e) { return false;} For me it was not so important to get it though. But at some point I noticed that I was getting an exception when the domain did not...

ZF2 DB Adapter - Column not found: 1054 Unknown column

mysql,zend-framework2

Ok, I don't know why it didn't work as before but it works when I move the keywordlink_ref_type = "product" into the where condition: SELECT product.*, COUNT(DISTINCT keywordlink_keyword_id) AS keyword_count FROM adcheck.product LEFT JOIN keywordlink ON keywordlink_ref_id = product_id WHERE keywordlink_ref_type = "product" AND product_deleted IS NULL GROUP BY product_id...

Bootstrap of Zend Module is not loading

php,zend-framework,autoload

I did some tests in my basic ZF1 setup and the only way this does not work is when the filename is not Bootstrap.php. In terms of Linux it is also case sensitive. As you mention correctly the modules path is looked at every time and exit() is working in...

Zend Skeleton Application album tutorial 404

php,zend-framework,zend-framework2

It turns out in module.config.php I had split the array with the controllers and router into two arrays by mistake. Combining them into one seems to have solved this particular issue. Code follows: return array( 'controllers' => array( 'invokables' => array( 'Album\Controller\Album' => 'Album\Controller\AlbumController', ), ), 'router' => array( 'routes'...

Socialengine addon Advanced Events Plugin v4.8.8p2 throwing errror on create

php,zend-framework,socialengine

Its seems you need to verify license .Contact the Socialengineaddson guys will help you.

BETWEEN with range including '1' also returns '10'

php,mysql,zend-framework2,between

After some digging through the ZF2 libraries, I found out that the Between predicate, always sets the input values to a TYPE_VALUE, which basically means the values get wrapped in quotes. One solution would be to change the Between class in the library to use a TYPE_LITERAL, but I think...

D2l first time signature is matched but next time, it displays authenticated signature?

php,api,zend-framework2,php-5.3,desire2learn

You should just clear session and cache,after logged out event. ...

Composer + Rocketeer + ZF2- Cannot install Rocketeer due to requirements conflict

php,zend-framework2,composer-php,rocketeer

Why doesn't it install? The installed dependencies of the Zend Skeleton use symfony/console in version 2.6.6. "anahkiasen/rocketeer" requires "illuminate/console" in a version ~4.2, which itself requires "symfony/console" in version 2.5.*. Composer cannot install the new package because the installed version 2.6.6 of symfony/console will be kept, but is incompatible to...

Zend Framwork 2 - Tablegateway - Updating only one column of a row in DB

php,mysql,database,zend-framework2,tablegateway

->update (array ('username' => $username), array ('id = ?' => $id)); Sorry for formatting, I am writing on phone. ...

PHP/Zend Framework 2 - Unable to display table field values within dynamically generated table

php,mysql,model-view-controller,zend-framework2

Answer The exchange array method shown below needs to have proper case for the $data array elements. I revised all lines starting with the sample one below to have the proper case. Since ActionItemID is a string it needs to have to the proper case of the ActionItemID. Answer Snippet...

Get Google Plus Images Using Zend Framework 1 Gdata

php,cakephp,zend-framework,google-plus,gdata

Zend_Gdata uses ClientLogin which was deprecated as of April 20, 2012 and turned off on May 26 2015. This code will not longer work you need to switch to using Oauth2. You can use the current Google PHP client library to authenticate then use the access token created there to...

Zend And YouTube Not Deleting Videos

zend-framework,youtube-api,google-client-login

Zend_Gdata uses ClientLogin which was deprecated as of April 20, 2012 and turned off on May 26 2015. This code will not longer work you need to switch to using Oauth2. You can use the current Google PHP client library to authenticate then use the access token created there to...

Zend Framework 2 - Showing the content of a database

php,mysql,database,pdo,zend-framework2

Your code looks good. The only issue I can see is that you are using the ClassMethods hydrator and you have no setters on your entity. The hydrator will use the entity API to hydrate the entity, if the setId, setName or setText are not callable then the values will...

Wrong datatype for referenced entity on Doctrine ObjectSelect

php,zend-framework,orm,doctrine2

What are your hydrator settings on this fieldset? For example; $this->setHydrator(new DoctrineHydrator($em, 'Blog\Entity\Category')) ->setObject( new Category() ); ...

How to make Zf2 Apigilty accept client request with no Accept set in header

php,zend-framework2,apigility,content-negotiation

You could write a listener in which you check the Accept header of the incoming request. If no Accept header is set you can add an Accept header with a default value; for example application/json. So something like: /** * Set empty accept header by default to `application/json` * *...

How can I make PHPUnit ignore a file pattern?

php,zend-framework2,phpunit

So, in order to exclude multiple files with the same name, <file> normally wont do a thing as it will only match a single file exactly. The solution is to use <directory>, but to use the suffix attribute; <phpunit bootstrap="tests/bootstrap.php" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true"> <testsuites> <testsuite name="Test Suite"> <!-- functional...