Coder Social home page Coder Social logo

contain's Introduction

Contain PHP Entity Models

Compiled lightweight entity models for PHP. Type validation, data encapsulation, filtering and validation without the ORM.

Entity Models

An entity model is a container for one or more pieces of data that describe something in your application. For example, a User model might be described as:

$user = array(
    'firstName' => 'Andrew',
    'lastName'  => 'Kandels',
);

Say you develop a service to create a user. There are two common ways to pass your model to that service.

Passing Arrays

class Service {
    public function addUser(array $data) {
        ...
    }
}

$service->addUser($user);

The problem with this approach is that the addUser method is only guaranteed to receive an array of data. It could be passed an empty array, an array with typos for its data (firstName -> first_name) or possibly even non-string values for its first or last name indexes.

Placeholder Parameters

class Service {
    public function addUser($firstName, $lastName) {
        ...
    }
}

$service->addUser('Andrew', 'Kandels');

The first problem with this approach is when you start creating larger models the exact position of each parameter becomes difficult to remember. PHP also doesn't supported named parameters like other languages. Removing parameters later could also break backwards compatibility.

PHP can't do type-checking on scalar values like strings either, so the service is still responsible for validating that $firstName is a string and not an object or something unusable.

Meet Contain

Contain aims to solve this problem by creating lightweight entity models that you pass between services, controllers, views and just about anywhere else in your application:

class Service {
    public function addUser(User $user) {
        ...
    }
}

$user = new User(array(
    'firstName' => 'Andrew',
    'lastName' => 'Kandels'
));

$service->addUser($user);

Contain takes care of these things for you with the entity model:

  • It encapsulates properties into a simple object (no isset() checks)
  • It creates simple setters and getters
  • It validates the types of properties
    • Strings are strings
    • Numbers are numbers
  • It converts properties to expected types
    • "2014-01-01" -> new DateTime(strtotime('2014-01-01'))

View the complete Project Documentation at http://www.contain-php.org.

contain's People

Contributors

akandels avatar ocramius avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

contain's Issues

Unit Test: ContainTest\Entity\StringTypeTest::testParseNoValue fails

  1. ContainTest\Entity\StringTypeTest::testParseNoValue
    Failed asserting that '' is null.

/Users/mwillbanks/Projects/contain/tests/Contain/Entity/Property/Type/StringTypeTest.php:20

I have not changed anything around this area; so I'm guessing that you may have made the change on purpose OR it's a ๐Ÿ›

Dynamic Field Support

While compiled entities provide the best performance and a larger degree of enforceability it does have drawbacks such as the inability to dynamically alter a document such that a "plugin" might do to add it's own data into the flow.

Take for instance a content management system or anything of the like. You might have a plugin that wants to store information on each post. It would be expensive to fetch that data from a separate collection rather than to store it in the same collection.

Therefore there are really a few different options here:

  1. Modify the entity definition through the use of events at compile time.
  2. Modify the entity by allowing more or less proxy methods.

In case 2 above you might use __call() and provide the logic for implementing the getter/setter based off of the definition. Otherwise the other route here is to simply fetch the properties and have to fetch them from the extended properties area.

Setting Properties does not run Validators

I'm not sure if it is intentional or not but since it is populated on the entity it would seem to me that the entity should run the validators against the entries.

Say for instance a validator on a number field; you give it a string value it will still populate and not complain.

by using Ajax in addaction and error msg not displaying from input factory,

$param = new Param();
$messages = array();
if ($request->isPost()) {

        $form->setData($request->getPost());
  echo 'hiiiiii'; 
       if (!$form->isValid()) 
      {
            $errors = $param->getInputfilter();
            foreach($errors as $key=>$row)
            {
                if (!empty($row) && $key != 'submit') {
                    foreach($row as  $rower)
                    {
                        //save error(s) per-element that
                        //needed by Javascript
                        $messages[$key][] = $rower;    
                    }
                }
            }
        }

// $messages=$form->setInputFilter($param->getInputFilter());
var_dump($messages);
if (!empty($messages)){
$response->setContent(\Zend\Json\Json::encode($messages));
} else
{
$response->setContent(\Zend\Json\Json::encode(array('success'=>1)));
return $response;
}

Generated Formatting

The generated formatting is; well.. ugly :) Might want to run php-cs-fixer on it or clean it up

Scripts: Support Modules not just Applications

There is a limited amount of work that you need to do in order to provide a way to support modules rather than having to support a whole application. Although since it is different I decided it might be best to open an issue about it.

fromArray() -> set extended properties when passed keys aren't properties

If model A has properties p1 and p2 and you call:

$a->fromArray(array('p1' => '1', 'p2' => '2', 'p3' => 3))

It should set properties p1/p2 as expected; but also set an extended property for "p3" to 3.

There shouldn't be any downside to this as extended properties are never exported -- just a little extra space.

MySQL Support...

Dude; need your help to write the driver part of this. I have the connection part (aka the easy part) done. Just working through the adapter and it is very mongolishious so I'm not quite sure where to put in some of the logistical items.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.