Jump to content

NotionCommotion

Members
  • Content count

    1,662
  • Joined

  • Last visited

  • Days Won

    6

NotionCommotion last won the day on June 18

NotionCommotion had the most liked content!

Community Reputation

25 Good

About NotionCommotion

  • Rank
    Prolific Member

Contact Methods

  • Website URL
    http://

Profile Information

  • Gender
    Not Telling

Recent Profile Visitors

The recent visitors block is disabled and is not being shown to other users.

  1. NotionCommotion

    Array help

    There are many ways, but the following should work. $arr2=array_values($arr2); foreach($arr2 as $key=>$value){ $arr1[$key][]=$value; } While array_merge() seems like what you want, if you don't want to reindex the keys, use $arr1+$arr2.
  2. NotionCommotion

    Compressing JSON transmitted by a socket

    Yeah, we discussed it here where you recommended using gzip/zlib encoding over CBOR or MassagePack. I thought there was more discussion than this but couldn't find it, but just did and apologize for the redundancy. Regarding your comment "Consider what it means to have a header", this is just related to error handling, true?
  3. I wish to compress JSON-RPC messages which are being transferred by a socket. Looks like using http://php.net/manual/en/intro.zlib.php won't work with sockets. Correct? Should one just call the appropriate function before sending and before reading the content? How do I determine which function to use? gzcompress/gzuncompress gzdeflate/gzinflate gzencode/gzdecode zlib_encode/zlib_decode
  4. If calling a parents constructor, it is considered better practice to duplicate the type declarations or just use them in the parent? Originally, I was doing for both, but it gets a bit cumbersome sometimes, and thinking of changing. Thanks namespace Base\Bla\BlaBla\Foo; class FooClass { protected $mapper, $validator, $pdo, $properties; public function __construct( Mapper\MapperClass $mapper, Validator\ValidatorClass $validator, \PDO $pdo, array $properties ) { $this->mapper=$mapper; $this->validator=$validator; $this->pdo=$pdo; $this->properties=$properties; } } Option 1 namespace Base\SpecificFoo; class SpecificFooClassx extends \Base\Bla\BlaBla\Foo\FooClass { protected $bar; public function __construct( Bar\BarClass $bar, $mapper, $validator, $pdo, $properties ) { $this->bar=$bar; parent::__construct($mapper, $validator, $pdo, $properties); } } Option 2 namespace Base\SpecificFoo; class SpecificFooClass extends \Base\Bla\BlaBla\Foo\FooClass { public function __construct( Bar\BarClass $bar, \Base\Bla\BlaBla\Foo\FooClass\Mapper\MapperClass $mapper, \Base\Bla\BlaBla\Foo\FooClass\Validator\ValidatorClass $validator, \PDO $pdo, array $properties ) { $this->bar=$bar; parent::__construct($mapper, $validator, $pdo, $properties); } }
  5. NotionCommotion

    Passing additional parameters to closure in the container

    Gotcha. Thanks!
  6. NotionCommotion

    Passing additional parameters to closure in the container

    Thanks requinix, Your example of wrapping in a second function makes sense and so does your statement regarding lazy loading versus being a factory as well as your recommendation not to use raw(). Not sure, however, about having "the second one in quotes". Just to confirm, the script you posted afterwards pertains to wrapping in a second function and not about factory "factory", correct? Please elaborate on this part. Thanks
  7. Slim automatically passes the container to closure defined in the container. How can an additional parameter be passed such as my someOtherService() example? Thanks <?php require '../vendor/autoload.php'; use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; $app = new \Slim\App(/* as applicable */); $c = $app->getContainer(); $c['someService'] = function ($c) { return 'someService'; }; $c['someOtherService'] = function ($c, $id) { return 'someOtherService'; }; $app->get('/endpoint/{id:[0-9]+}', function (Request $request, Response $response, $args) use ($c) { //The following will all pass the container to someService and I believe are all identical ways to perform the same thing $someService1=$c['someService']; $someService2=$c->get('someService'); $someService3=$this->someService; //The following will not work since only the container is first passed to someOtherService() $someOtherService1=$c['someOtherService']($c, $args['id']); $someOtherService2=$c->get('someOtherService')($c, $args['id']); $someOtherService3=$this->someOtherService($c, $args['id']); });
  8. NotionCommotion

    Using Slim with a factory

    Let me rephrase the question. How can I inject content into an object when that content is not know when defining that object in a container?
  9. NotionCommotion

    Using Slim with a factory

    The intent of the following script is to receive an ID in the endpoint, determine what type of record it represents, and create the appropriate object to deal with it. There are two related aspects which I think should be done different, but I don't know how best to do them. Both require to be injected with some other data, and I've taken two approaches. MyValidator is wrapped in a second closure and then invoked with the applicable data. SpecificFactory is not wrapped in a second closure, but then needs an initializing init() method to make it usable. Neither seem like the right approach. Any recommendations? require '../vendor/autoload.php'; use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; $app = new \Slim\App(/* as applicable */); $container = $app->getContainer(); $container['pdo'] = function () {/* as applicable */}; $container['myValidator'] = $container->factory(function ($container) { return function ($userData, $validationRules) use ($container) { return new MyValidator($userData, $validationRules, $container['pdo']); }; }); $container['specificFactory'] = function ($c) { return new SpecificFactory($c); }; $app->put('/some/end/point{id:[0-9]+}', function (Request $request, Response $response, $args) { $factory=$this->specificFactory->init($args['id']); $rs=$factory->getService()->create($request->getParsedBody()); return $factory->getResponder()->create($response, $rs); }); $app->put('/some/other/end/point{id:[0-9]+}', function (Request $request, Response $response, $args) { $factory=$this->otherFactory->init($args['id']); $rs=$factory->getService()->create($request->getParsedBody()); return $factory->getResponder()->create($response, $rs); }); $app->run(); abstract class Factory { protected $container, $properties; public function __construct(\Slim\Container $container) { $this->container=$container; } public function init($identifier) { if(ctype_digit($identifier)) { if(!$this->properties=$this->getProperties($identifier)) { throw new FactoryException("Invalid identifier ID '$id'."); } } elseif(is_string($identifier)) $this->properties=['type'=>$identifier]; else throw new FactoryException('Invalid identifier'); return $this; } public function getService() { if(!$this->properties) throw new FactoryException('Factory must be initialized first'); if(!$service = $this->getServiceObject()) throw new FactoryException('Invalid entity type'); return $service; } public function getResponder() { if(!$this->properties) throw new FactoryException('Factory must be initialized first'); if(!$responder = $this->getResponderObject()) throw new FactoryException('Invalid entity type'); return $responder; } abstract protected function getProperties($identifier); abstract protected function getServiceObject(); abstract protected function getResponderObject(); } class SpecificFactory extends Factory { protected function getProperties($id) { $stmt = $this->container['pdo']->prepare(/* ... */); $stmt->execute([$id]); return $stmt->fetch(\PDO::FETCH_ASSOC); } protected function getServiceObject() { switch($this->properties['type']) { case 'type1': return new Type1\ServiceType1( new Type1\MapperType1( $this->container['pdo'], $this->properties ), ($this->container['validationService'])('rules1', $this->properties), $this->properties ); break; case 'type2': return new Type2\ServiceType2( new Type2\MapperType2( $this->container['pdo'], $this->properties ), ($this->container['validationService'])('rules2', $this->properties), $this->properties ); break; case 'type3': return new Type3\ServiceType3( new Type3\MapperType3( $this->container['pdo'], $this->properties ), ($this->container['validationService'])('rules3', $this->properties), $this->properties ); break; default: return false; } } protected function getResponderObject() { switch($this->properties['type']) { case 'type1': return new Type1\ResponderType1(); break; case 'type2': return new Type2\ResponderType2(); break; case 'type3': return new Type3\ResponderType3(); break; default: return false; } } } class ServiceType1 { protected $mapper, $validator, $properties; public function __construct($mapper, $validator, $properties) { $this->mapper=$mapper; $this->validator=$validator; $this->properties=$properties; } public function update($userData) { $myInjectedValidator=($this->container['myValidator'])($userData, ['validationRules']); if($myInjectedValidator->isValid()){ $this->mapper->update($userData); } else throw new Exception('bad data'); } } class MyValidator { protected $userData, $validationRules, $pdo; public function __construct($userData, $validationRules, $pdo) { $this->userData=$userData; } public function isValid() { return rand(1); } }
  10. Is there any order variables injected in the constructor and then the parent's constructor more typically used than the other or considered best practice? I believe the last example is less than desired, but feel the first two both have their merits. EDIT. I guess if one every uses defaults in a constructor, then the first option is best. class ParentClass extends ChildClass { public $obj1; public function __construct(Class1 $obj1, Class2 $obj2, Class3 $obj3) { $this->obj1=$obj1; parent::__construct($obj2, $obj3); } } class ParentClass extends ChildClass { public $obj3; public function __construct(Class1 $obj1, Class2 $obj2, Class3 $obj3) { $this->obj3=$obj3; parent::__construct($obj1, $obj2); } } class ParentClass extends ChildClass { public $obj2; public function __construct(Class1 $obj1, Class2 $obj2, Class3 $obj3) { $this->obj2=$obj2; parent::__construct($obj1, $obj3); } }
  11. NotionCommotion

    Composition over inheritance examples

    I like your "is a" and "made from" tests. For a simple applicable, inheritance is simple and concise, but the class size and complexity will increase as functionality is added and there is the potential that functional requirements will diverge. At that time, I will ask myself what abstract concept is it made from and break it out. I am sure it will take time and practice, but think it is a good start. I even pinned a sticky note (something I never do) stating these two tests so I don't fall out of the habit of asking myself them.
  12. NotionCommotion

    Composition over inheritance examples

    For my Admin/User/Person example, maybe an Admin is just a Person but I don't inject an Admin into a Person but inject an AdminControlPanel which provides the capability of an Admin? Not sure how this would work with injecting an AdditionalBarChartCapabilities into a Chart.
  13. NotionCommotion

    Composition over inheritance examples

    I've definitely personally experienced improper use of inheritance which resulted in a complicated and inflexible mess. I am not saying that inheritance is evil or shouldn't be used, but just when misused, yeah, maybe "evil" is the right word. So, I've looked for opportunities to change the behavior of some of my classes by injecting different objects, and have found a few which has greatly simplified matters. But I still struggling to identify more opportunities. Most of the examples I read seem to be all the same and describe injecting an area calculator in a shape or a database interface in a mapper or some other simple example. While this is great, often it is not some defined "thing" I need to inject but a collection of behaviors which I can't seem to define a name for. For instance, we might have Admin extends User extends Person which seems good on the surface, but then I have a need for an Admin who isn't a user and things get wonkie. So, instead I could inject a Person in an Admin, but I've been told that injecting some subset class into a class (i.e. inject a barchart into a chart) isn't right either. So, where am I going with this? I guess I need just more real examples how it is done right. Any recommendations where I might find some (ideally in PHP)? Also, how would you handle the Admin/Person example without using Inheritance? Thanks
  14. NotionCommotion

    Should mappers digest objects?

    Maybe so, but sometimes you need to do it the hard way to appreciate what you have. I still remember wood shop when we had to sand our first project by hand before being able to use power sanders.
  15. NotionCommotion

    Should mappers digest objects?

    I have a bit to learn. Store (I think you like the word "esque". Had to look it up a few posts ago), mappers that fire off (who would have know they would do such?), ghost copy (sounds scary), and the like. That being said, most of it is starting to make sense just by doing (except for those damn ghosts!). Would it be wrong to think that why it seems so foreign to me is that I am not using a proper ORM like Doctrine? Just grasping for excuses... One question. Why should I avoid any createFromArray or updateFromArray methods?
×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.