PHP - Moved: Usage Of Dependency Injection Design Pattern
This topic has been moved to Application Design.
http://www.phpfreaks.com/forums/index.php?topic=346818.0 Similar TutorialsI'm trying to use dependency injection to pass a database connection to an object but I'm not sure why it's not working. I have my "dbClass" below that connects to a MySQL database. Code: [Select] class dbClass { public $db; function __construct() { $this->db = mysql_connect("localhost","username","password") or die ('Could not connect: ' . mysql_error()); return $this->db; } } Then I have my "baseClass". This is the class that I want to feed to connection too. Code: [Select] class baseClass { public $mysql_conn; function __construct($db) { $this->mysql_conn = $db; $rs = mysql_select_db("webdev_db", $this->mysql_conn) or die ('Could not connect: ' . mysql_error()); } } And this is my index.php file. The error I'm getting is "supplied argument is not a valid MySQL-Link resource". However I tripled checked and my db connection details are definately correct. Code: [Select] $db = new dbClass(); $baseclass = new baseClass($db); Thanks for any help. I need to create an entity which models the connection between a PHP server and another device so that a web app can change the entity's properties which in turn will update the server DB as well as the other device. A little background information for context is as follows: When a socket clients connects to the PHP server, it will register by providing its GUID, and in turn the server will query its DB to identify the specific client. The client has various other properties associated with the socket connection such as reconnect_timeout, response_timeout, etc, and the associated values will also be stored in the server's DB. While all socket clients use the same approach to communicate to the PHP server, several "flavors" of socket clients exists which use a specific protocol (Modbus/RTU, Modbus/IP, ControlNet, BACnet/IP, BACnet/MSTP, KNX, DALI) to communicate to downstream devices. Based on the used protocol, there will be different properties as well as different methods (i.e. some protocols allow one to query the device to retrieve a list of available data). To create the entity using inheritance, I would likely do so whe class ModbusRtuSocketClient extends ModbusSocketClient (which extends SocketClient) class ModbusIpSocketClient extends ModbusSocketClient (which extends SocketClient) class ControlNetSocketClient extends SocketClient etc.. But instead of doing so by using inheritance, I am thinking that I should do so through injection. For instance, I create an object called SocketClient which just deals with that scope of work and is protocol agnostic. I also create a second object which deals with a given protocol such as ModbusRtuProtocol extends ModbusProtocol extends Protocol. I then do one of the following: $entity = new SocketClient(new ModbusRtuProtocol()); //or $entity = new ModbusRtuProtocol(new SocketClient()); //and do $entity->setSomeSocketClientProperty(123); $entity->getProperty()->setSomeSpecificProtocolProperty(321); $entity->updateEndDevice(); $entityManager->persist($entity); $entityManager->flush(); //or do $values=$entity->queryDevice();
PS. If you think I shouldn't be doing so through injection but through inheritance, please advise.
Could use some help with dependency injection, as I can't seem to find the answer anywhere. Ok, take a quick PHP class:
<?php namespace myapp; use myapp\template; use myapp\order; class user { private $template; public function __construct(template $template) { $this->template = $template; } public function add_order(order $order) { // do something with $order here } }
I'm using the php-di package from http://php-di.org/ right now, but open to changing. My question is, how do I call that "add_order()" method, and have $order injected into it? Constructor injection is easy, and just use:
$container = new Di\Container(); $container->make(myapp\user);
How do I do that, but calling the add_order() method instead? I want something like:
$container = new Di\Container(); $container->make(myapp\user::add_order);
Any help?
Thanks, Matt
I'm looking for some clarification here from different viewpoints to understand real world applications. In a previous thread, I suggested to someone that they read up on singleton methods to restrict class duplication (oops!), I was quickly (and rightfully) shot down. I did this after having read through blog posts that also suggested singleton design to stop multiple MySQL connections. At the time I didn't consider that could be useful to some people.. fair enough. Thankfully I don't use singleton methods within my own code, but I do use static methods for most things. Reading through numerous blog posts, tutorials, etc.., it seems like static methods can also be considered anti-design and is something to avoid. So now it seems I'm at a point where I need to rewrite my existing framework & CMS, probably using dependency injection within my classes. I understand how this works, and why it makes sense. What I'm struggling with is understanding how to use dependency injection within a (personal) CMS application. For example - I have a config.ini file I have a class that reads the .ini file, stores the variables, and provides me methods to access them I have a content class that selects the relevant page/component from the DB (db & config dependency), then displays it via my template engine. Within the included view files I call component classes (articles, contact, etc..), each of these require a connection to the DB, which has a config dependency. Here's some code to explain it better - index.php <?php $settings = '/config/config.ini'; $config = new Config($settings); $db = new Database($config); $content = new Content( $db ); // Config may also be passed for content config - keeping it simple for example print $content->loadPage($_GET['page']); // This would now include the code below ?>Let's say that this then loads the article index (through $content->loadPage()). The view would look something like this - article_index.php <?php // Duplicated code $settings = '/config/config.ini'; $config = new Config($settings); $db = new Database($config); // Article code $articles = new Articles_Model($db); return $articles->getArticles(0,15); ?>Now my problem is that I'm duplicating the config and db class calls for no reason. Is the sollution to store these within a registry class? But then I'm creating globals, which again seems anti-design. Or is the problem how I load the active page? Any insights would be much appreciated. Was just wondering why some people choose NOT to make use of static functions when initializing objects via Factory Classes/Containers. What are the benefits of initializing the Factory class when for all intensive purposes, it's only used to initialize new classes, etc? Does this have any impact on Dependency Injection? I'm assuming that it doesn't since that would defeat the purpose. --------- Also, I've noticed that there seems to be an intense stigma within the development community in regard to singletons. Are singletons necessarily a bad thing? What about database objects? One argument I've heard is that this can often impact the flexibility of your application in the event that a new instance of said class needs to be initialized(a second completely separate connection). However, I was thinking that you could simply store these objects within a static member variable in the factory class; leaving the Database Class' __construct public in the event that you need to create that second/third/fourth connection. Wouldn't this resolve the issue? This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=320813.0 This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=306005.0 This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=319964.0 This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=347558.0 This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=322578.0 Hey guys. So I'm trying to write a script that replaces footnote citations in one format with footnote citations in another format. For example, the text will read: "Then he went down the street.[1] That is where the police found him [2]. They immediately arrested him at the house. [3]" And I would like the script to find the [ #] strings and replace them with {#} ... so that the string reads: "Then he went down the street.{1} That is where the police found him {2}. They immediately arrested him at the house. {3}" Note that there will be double, and even tripple, digit footnotes, so the script has to be able to recognize [##] or [###] and replace the brackets with {} accordingly. I'm not really sure how to do this, since the "pattern" is constantly changing depending on the number between the brackets. Ideas? Thanks! the difference between memory usage and bandwidth usage? I did a test with 500 rows in table, got 2.36mb memory usage, and then once without 500 rows in table, i got 2.34 (IN MBS) memory usage, can that translate into bandwidth usage? somone told me that bandwidth usage != memory usage, how so? it does effect it some doesn't it ? This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=357188.0 Amazingly, threads about application design belong in the Application Design sub-forum. This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=358384.0 This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=318519.0 This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=327717.0 This topic has been moved to Website Critique. http://www.phpfreaks.com/forums/index.php?topic=346717.0 I just updated a site as follows: cd /var/www/concrete5 composer update Among other changes, the following were made (more on this later): - Updating concrete5/core (8.5.2 => 8.5.4): Downloading (100%) - Updating doctrine/collections (1.6.4 => 1.6.5): Downloading (100%) - Updating doctrine/lexer (1.2.0 => 1.2.1): Downloading (100%) - Updating doctrine/inflector (1.3.1 => 1.4.3): Downloading (100%) - Updating doctrine/cache (1.10.0 => 1.10.1): Downloading (100%) - Updating doctrine/annotations (1.10.2 => 1.10.3): Downloading (100%) - Updating doctrine/common (2.12.0 => 2.13.3): Downloading (100%) - Updating doctrine/instantiator (1.3.0 => 1.3.1): Downloading (100%) - Updating doctrine/orm (v2.7.2 => v2.7.3): Downloading (100%)
errno: 150 "Foreign key constraint is incorrectly formed I expected I should have first used concrete5's update script, but too late for that. So, then I changed composer.json require concrete5/core from ^8.5 to 8.5.2 hoping to return to the previous state. Concreete5 was downgraded as desired, but now I get the following error: Class 'Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain' not found On another concrete5 site which still works, I have the following two files, however, on the broken one I only have the second: vendor/doctrine/persistence/lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php:13: class MappingDriverChain extends \Doctrine\Persistence\Mapping\Driver\MappingDriverChain vendor/doctrine/persistence/lib/Doctrine/Persistence/Mapping/Driver/MappingDriverChain.php:17:class MappingDriverChain implements MappingDriverSo, now I will attempt to downgrade doctrine from 2.7.3 to 2.7.2. The base composer.json file has no reference to Doctrine, but there are two other related composer files: vendor/concrete5/doctrine-xml/composer.json { "name": "concrete5/doctrine-xml", "description": "Define database structure via XML using Doctrine data types", "keywords": [ "doctrine", "xml", "structure", "database", "schema" ], "homepage": "https://github.com/concrete5/doctrine-xml", "license": "MIT", "autoload": { "psr-4": { "DoctrineXml\\": "src/" } }, "require": { "php": ">=5.3" }, "require-dev": { "doctrine/dbal": "2.5.*" } } vendor/concrete5/dependency-patches/composer.json { "type":"library", "license":"MIT", "name":"concrete5/dependency-patches", "description":"Patches required for concrete5 dependencies", "homepage":"https://github.com/concrete5/dependency-patches", "authors":[ { "name":"Michele Locati", "email":"michele@locati.it", "role":"author", "homepage":"https://mlocati.github.io" } ], "require":{ "mlocati/composer-patcher": "^1.0.0" }, "extra":{ "patches": { "doctrine/annotations:1.2.7": { "Fix access array offset on value of type null": "doctrine/annotations/access-array-offset-on-null.patch" }, "doctrine/orm:2.5.14": { "Fix UnitOfWork::createEntity()": "doctrine/orm/UnitOfWork-createEntity-continue.patch" }, "zendframework/zend-stdlib:2.7.7": { "Fix ArrayObject::unserialize()": "zendframework/zend-stdlib/ArrayObject-unserialize-continue.patch" }, "sunra/php-simple-html-dom-parser:1.5.2": { "Fix minus in regular expressions": "sunra/php-simple-html-dom-parser/minus-in-regular-expressions.patch" }, "phpunit/phpunit:4.8.36": { "Avoid each() in Getopt": "phpunit/phpunit/Getopt-each.patch" }, "tedivm/jshrink:1.1.0": { "Fix continue switch in Minifier": "tedivm/jshrink/fix-minifier-loop.patch", "Update to upstream version 1.3.2": "tedivm/jshrink/update-upstream-1.3.2.patch" }, "zendframework/zend-code:2.6.3": { "Fix continue switch in FileGenerator and MethodReflection": "zendframework/zend-code/switch-continue.patch" }, "zendframework/zend-http:2.6.0": { "Remove support for the X-Original-Url and X-Rewrite-Url headers": "zendframework/zend-http/no-x-original-url-x-rewrite.patch" }, "zendframework/zend-mail:2.7.3": { "Fix idn_to_ascii deprecation warning": "zendframework/zend-mail/fix-idn_to_ascii-deprecation-warning.patch" }, "zendframework/zend-validator:2.8.2": { "Fix idn_to_ascii/idn_to_utf8 deprecation warning": "zendframework/zend-validator/fix-idn_to_-deprecation-warning.patch" } } } } Neither seem to be applicable, but the doctrine version has to be specified somewhere. How does composer determine which version and how can I downgrade the dependency package? Thanks
PS. As a hack solution, I replaced the entire vendor/doctrine directory from one from another site, and have things working. Still, want to know how to do this right. Edited June 12, 2020 by NotionCommotionI am on a shared hosting server running CentOS. I have copied a PHP extension (imagick.so) that was built on similar server to my shared hosting server. I have resolved most of the dependencies by placing the missing files in ~/lib but I have one that I can't figure out how to cope with. I am getting the following error: Hi, My hosting disabled my account because my site used too many system resources (CPU). There is no way for me to know how much CPU my site is using since i am not a psychic or god so no clue how they expect me to monitor this or fix this (the site has been running just fine for 2 years with the same code). Is there any code that can tell me how much CPU my site is using on the server? Thanks in advance, Jay |