PHP - Factory Pattern And Autoloading.
Hello
I hear alot of talk about reusing a database connection and attempts to solve this.
I came across this post on stackoverflow but am having difficulty understanding as to how this is any different than just creating a instance in a single file and including it via include, require or autoload wherever a db instance is needed.
The pattern talked about in the post is the factory pattern, it seems that the factory is responsible for creating the instance, something which I thought autoloading did without this additional code?
Another thing I am still confused by with all the reuse talk - If 2 seperate users request 2 different pages on our server(2nd user 0.1 second behind the other user) which both refer back to the same db file/factory, are 2 instances created? or is the previuos users instance somehow used aslong as there request has not finished?
I thought that the server would make new fresh requests/variables/instantiation etc all over again for every user, perhaps I am wrong.
Thanks in advance.
Edited by RuleBritannia, 13 May 2014 - 05:15 PM. Similar TutorialsSo I was stumbling around with Repositories and Interfaces and got a decent grasp on it. However, I started running into abstraction and started to implement a little bit of the Factory design.
How often is this typically used? It seems like I should be using Factory with 90% of my Repositories since there are different types of Items, Tutorials, Random Events, etc.
Items
- Food
- Weapon
- Toy
Tutorials
- Newbie
- Farming
Random Events
- Coin Giving
- Item Giving
- Item Draining
Things like this... so all of them have similar methods involved. So they each have a base method, for example.. an Item child class would always have the use() method and a factory would determine which kind of object to initiate from your controller just from the item model being passed through. So therefore you can call use() on the repository instance it returns.
Then I was moving onto my tutorials and random events and it just seemed very similar.
So in most cases, will factories be a huge plus? Just wanted some general opinions from the PHP developers =)
Thanks!
Hi All,
I've been interested in writing a PHP pdo configuration file so that I can include connections in various files on my site. While I was looking up some possible solutions I stumbled across an interesting post on stack overflow http://stackoverflow...-pdo-connection
The first responder suggested the code below. However, I don't understand how to access the connection and make query calls. I'm confused by how it's possible to return a variable name as an object { return new $name( $this->connection ) }.
Also, If someone could explain what the author means by { $something = $factory->create('Something');}. Wouldn't the "Something" need to be a class? And how would that class get the db connection?
All the best,
Karma
$provider = function() { $instance = new PDO('mysql:......;charset=utf8', 'username', 'password'); $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); return $instance; }; class StructureFactory { protected $provider = null; protected $connection = null; public function __construct( callable $provider ) { $this->provider = $provider; } public function create( $name) { if ( $this->connection === null ) { $this->connection = call_user_func( $this->provider ); } return new $name( $this->connection ); } } $factory = new StructureFactory( $provider ); $something = $factory->create('Something'); $foobar = $factory->create('Foobar'); 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! hey guy I've just recently re-altered my autoloader class which works with namespaces but it also calls classes which aren't namespaced, like so:
$class = new myclass();instead of $class = new Class\Myclass;im wondering have i defeated the whole point of namespacing and if all my classes should actually be namespaced hope its not such a pointless question
Hallo, I have a strange problem with a freshly installed composer project that is not loading the dependencies as the documentation states it should. composer require phpmailer/phpmailer
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); // define('BASE_PATH', rtrim(preg_replace('#[/\\\\]{1}#', '/', realpath(dirname(__FILE__))), '/') . '/'); // require BASE_PATH . 'vendor/autoload.php'; require __DIR__ . '/vendor/autoload.php'; Edited June 23, 2020 by JacobSeated 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? Hey Guys. I am learning about the Enterprise pattern, and to me it seems like its the same as the MVC pattern (which I learned about)
Do they work the same??
For those who know Martin Fowler's Patterns of Enterprise Application Structure, that is what I am referring to as the enterprise pattern
Edited by eldan88, 13 October 2014 - 10:24 AM. How to make "hints" as dynamic varaible: (example I looked at: http://develturk.com/tags/selfinstance/) I've looked into the singleton pattern and a few examples. I've understood most of its concept, but I still have a few things puzzling me. I noticed that you're not supposed to allow cloning (obviously) or the construction method as it shows in an example: //this object can not copy //except the getInstance() method. private function __clone() {} //prevent directly access //we want acces this only from getInstance method. private function __construct(){} Do I also have to do this for child classes, or just the parent class? I have a questions regarding Singleton Pattern in this video: http://www.youtube.com/watch?v=-uLbG7nJCJw&feature=plcp&context=C49f92beVDvjVQa1PpcFMxdGEHDoxYON2LEGpH0krK5UV1HfoVHGM= Using the singleton pattern, isn't possible to have methods that aren't static? In this video it shows nothing but static methods. Also, after creating the class object like so: $database = Database:Connect(); How would I go about using normal functions with that object? Say I had a query function. I can't do this: $database->query(); So what would I do? :/ - Thanks for any help regarding this. I'm trying to preg_match $text for specific words, defined in an array. $text = "PHP is a programming language of choice"; $text = "This is a function written in a programming language called PHP."; $words = array("/java/", "/PHP/", "/html/"); for ($i = 0; $i < count($words); $i++) { preg_match($words[$i], $text, $matches); }The problem with tis is that it returns 3 arrays, of which only the second one is a match, and the other 2 arrays are empty. The result is that I get notice error on my echo page because the 1st and 3rd arrays are empty. if I want the text to be searched for the first matching result, whether it is java, PHP or html, then stop (if possible) and echo/return the result, how will I do that? Perhaps preg_match is not to be used here but instead something like substr? I am trying to find the last word before a search pattern. I tried preg_match without any luck. I found something close online but it does a match for the first match for the pattern. I know that I will always see , some # pressure. I want that # right before the word pressure but there are a lot of , in the page. Thanks in advance. Code: [Select] function get_string_between($string, $start, $end){ $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } $fullstring = "today, Sat, 750 pressure"; $parsed = get_string_between($fullstring, ", ", "pressure"); Hello,
I have a file to display
$file_content = file_get_contents("test.php");This file is encoded.... In this file there is a specific tag call change_me <change_me> "<code> <strong>Example Element</strong> </code>" </change_me>I want to use htmlspecialchars_decode function for <change_me> tag only... <change_me> tag is used two times in file. Thanks Edited by arunpatal, 10 July 2014 - 04:15 PM. For example: $text = preg_replace_callback( "/([@][a-zA-Z-0-9]+)/" , "umentions", $text, 1);That 1 parameter means the maximum times it will iterate right? So If I'm doing: @Nexus @Cupcake @George it will return: My problem is. I only want it to iterate over the last match in my function: function umentions($matches){ vdump($matches); return "(here you would replace: ".$matches[0]." with something)"; }How is it possible to use limit, and only iterate the last match not the first? Edited by Monkuar, 22 January 2015 - 08:46 AM. Hiya peeps! I can't seem to build a preg_match pattern that works. This is what I need to do. "[" . $errorID . "]='HERE IS WHAT I NEED TO DISPLAY';" Does anyone have any ideas on how I would build this regex string? Many thanks, James. Hi all I have this simple gd code to produce a filled rectangle with a solid color. Code: [Select] <?php header('Content-Type: image/png'); $im = imagecreatetruecolor(1000, 200); $gray = imagecolorallocate($im, 240, 240, 240); imagefilledrectangle($im, 0, 0, 1000, 199, $gray); imagepng($im); imagedestroy($im); ?> Is it possible to create a rectangle with a pattern such as a lined background. GD Library Pattern Background ? Hi all I have a simple page here that uses the GD Library to display text in a selected font and size etc. http://www.ttmt.org.uk/forum/ At moment the stripped background goes from the code. Is there a way to have an image as the background instead of the stripped background. PHP code Code: [Select] <?php header('Content-Type: image/png'); $im = imagecreatetruecolor(900, 215); $w = imagecolorallocate($im, 255, 255, 255); $c = imagecolorallocate($im, 220, 220, 220); $black = imagecolorallocatealpha($im, 0, 0, 0, 20); $style = array($w,$w,$w,$c,$c,$c); ImageSetStyle($im, $style); ImageLine($image, 100, 0, 50, 50, IMG_COLOR_STYLED); imagefilledrectangle($im, 0, 0, 900, 214, IMG_COLOR_STYLED); $text = $_GET['text']; $textSize = $_GET['size']; $font = $_GET['font']; imagefttext($im, $textSize, 0, 15, 165, $black, $font, $text); imagepng($im); imagedestroy($im); ?> In the below example, we match 0 or more alphanumeric characters in the beginning and 0 or more alphanumeric characters in the end. Then we create 4 groups. Each group has "?=" which means "the next text must be like this". Now in first group we match any character 8 or more times. The next group we match 0 or more characters and a digit. In the next group we match 0 or more characters and a lowercase letter. In the next group we match 0 or more characters and an uppercase letter.
<?php $password = "Fyfjk34sdfjfsjq7"; if (preg_match("/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/", $password)) { echo "Your passwords is strong."; } else { echo "Your password is weak."; } ?>My question is do these four groups impact each other? That is, the fact that the first group has 8 or more characters means that all the groups must have 8 or more characters. The fact that the second group has a digit means that all the groups must have a digit. Or do they work exclusively meaning that a 4 character word with a single digit would match this pattern, even though first group says it must have 8 characters. This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=306005.0 $pattern="/[+][0-9]+[^a-zA-Z*-+!|@#$%&*(){\/}]/"; // $subject="+3706*0805595"; $ans=preg_match($pattern, $subject, $matches); print_r($matches);echo "ans=".$ans;gives output Array ( [0] => +3706 ) ans=1Where is my mistake. How to formulate pattern which does not accept string which contains letters or special characters. String must start with +, contain digits. |