Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
McGlockenshire
Dec 16, 2005

GOLLOCKS!

cLin posted:

I'm not sure if this belongs here but does anyone have any recommended reading on APIs? It seems like it's common knowledge yet I have no idea on how to use them (for example, something like logging in thru digg using their API).

I'm pretty familiar with PHP but everytime I read something on how to use X API, it goes over my head.

API translates to "the way to interface with our poo poo."

Most websites (Digg) have a web services API. You make requests to their site using certain URLs and certain query string or POST parameters, and you get data back, usually in JSON, sometimes in XML, or whatever they want.

There are a handful of web service API types. The most modern and trendy is "REST", which is another way of saying "use the HTTP verbs (GET, POST, PUT, DELETE, etc) to access resources." For example, sending "DELETE /post/1234" would delete that object. Often, REST-ful web services return data in JSON.

There are other, older ways to do web services. SOAP is one of the more convoluted and evil ways. It's a pain in the rear end wrapped in XML, and should be avoided if you don't want to lose your mind.

Sometimes the API is only exposed through code. They'll give you a set of files that usually contain a class or fifteen, and then the documentation on using the classes to do their thing. You'll usually find these monstrosities are in Java, and even though they use SOAP or something similar, they'll force you to use their code instead of giving you the API documentation because they are fucktarded. This unfortunate method has also been seen in .Net land, and is often used by "Enterprise" systems, because they take themselves too seriously and don't know how to version a web service / their toolset prevents them from implementing a versionable web service.

Does this help in the least?

McGlockenshire fucked around with this message at 04:12 on Jul 26, 2009

Adbot
ADBOT LOVES YOU

McGlockenshire
Dec 16, 2005

GOLLOCKS!

insidius posted:

I have the following so far:
Assuming that you want older rows red and newer white, your code had the comparison wrong. Other than that, it should work perfectly well. Any other changes would be stylistic:
code:
$time_span = 60 * 60 * 24 * 14;
$now = time();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $colour = "#FFFFFF";
    if(($row['lodged_date'] + $time_span) < $now)
        $colour = "#FF0000";
    // ...
- The color will always be white unless changed. No need for the else.
- No need to re-evaluate time() every row, even though that's a pretty simple operation.
- The number 1209600 has no immediate meaning. Splitting it out into the seconds -> minutes -> hours -> days math makes it pretty obvious to figure out what the span is (14 days)
- Color either does or does not have a U. Comment consistency with variables would be nice, but I'm really just being a nitpicker.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Most interestingly and/or horrifyingly, it's possible to get zero, null, and -1 error states depending on how bad the input is.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

quote:

Is there a non hack way to deal with dynamic mysqli prepared statements?

Can't use PDO instead?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

haywire posted:

I read somewhere that PDO was significantly slower than mysqli/mysql. If I'm wrong, please say. I really like PDO but this is going to need to be as fast as possible.
Unless you're making tens of thousands of queries in a single script run and need it NOW NOW NOW NOW NOW NOW NOW you won't notice any slowdown. I've never noticed any performance difference. Even then, if performance is what you're looking for, why are you working with PHP? ;)

quote:

Also, doesn't PDO have pretty much the same issue?
What issue? You have a query, you have the placeholders, you have a list of stuff to replace the placeholders with. Maybe I don't really understand what problem you're encountering...

Mr Viper posted:

Does anyone know of a guide to successfully installing phpMyAdmin?
1) Unzip.
2) Use the included configuration utility (in like /setup/ or /configuration/ or /install/ or something like that) to create your config.inc.php file
3) Copy the created file into the right place and nuke the setup directory
4) Works!
But what you have now looks like it SHOULD work...

But

quote:

this is hilarious. Google suggests that you're either hosted on Windows using a MySQL 4.1 Alpha, or your host's configuration is excessively hosed up...

McGlockenshire
Dec 16, 2005

GOLLOCKS!

haywire posted:

Yeah that part isn't hard, it is the binding of those parameters to things. I don't think PDO has this issue, on reflection. mysqli_stmt::bind_param has the most loving retarded syntax ever.

Ah, yes, now I understand.

Unfortunately I don't know of anything short of a custom solution that fixes the problem. It was one of the things that drove me up the wall when switching to PHP from Perl. With DBI, you can just pass in an array reference, and it'll automatically understand to use that for one and only one placeholder...

McGlockenshire
Dec 16, 2005

GOLLOCKS!
None, because It's Not The PHP Way.

Get out while you still can.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Thibaw posted:

Does anyone know, if it is required to compile php with --debug-enabled in order to be able to use the full functionality of xdebug?
xdebug does not require a recompile of PHP with the debug flag.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Hanpan posted:

If I have an array, which contains a bunch of assoc arrays, is there a way to pass this array directly to the execute function without having to bind each param?

Nope. The problem is that PDO thinks that there can be one and only one value for every placeholder, and is intentionally not smart enough to flatten arrays.

Your best bet is to create classes that inherit from PDO and PDOStatement (use $db->setAttribute(PDO::ATTR_STATEMENT_CLASS, 'Classname') to set it up) to wrap query() / execute() so that it flattens arrays and/or finds the placeholder and expands it as required. Using question mark placeholders instead of named placeholders can make this much easier.

Creating something that inherits from PDO is not a bad idea anyway, as then you can add happy convenience functions that PDO is missing.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

DirtyDaub posted:

The problem is, I cant figure out how to style the old locator to make it match the new site because it uses some style template written in XTPL, and I cant find any documentation about it.

I hate to be that guy, but it took me two seconds with Google to find that XTPL refers to PHP XTemplate. That's a link to the docs.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

quote:

Upgrading to a VPS solution is not realistic; it would cost more in a month than I had been signed up to pay in a year.
You get what you pay for. That cheap $5 a month hosting plan is shared with probably a few hundred other sites, just to keep the server profitable.

VPSes aren't expensive, most quality VPS hosts have plans starting at about $20/month.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

isagoon posted:

On the whole templates topic...

I rewrote some of my block processing code, and I have this. IS there any way to catching parse errors in the included code? I think I have seen Magento do it.

Parse errors are an uncatchable fatal.

If you're letting users edit templates via your UI, you can probably just shell out to php -l -- that's a lowercase L. This'd be impractical (slow) to do every time you include the template.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
The regex "^[a-zA-Z0-9\-]" says "find one lowercase/uppercase/number/dash at the beginning of the string". You probably want to move the caret inside the square brackets, "[^a-zA-Z0-9\-]", which means "find anything that is not a lowercase/uppercase/number/dash" instead.

What's var_dump($_GET['dir']) before and after the regex?

No idea where the .htaccess is coming from.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Do a var_dump on $result. Is it false? If so, check mysql_error().

McGlockenshire
Dec 16, 2005

GOLLOCKS!

gwar3k1 posted:

Is PDO's bindparam secure enough to do the following?:
If by "secure enough" you mean "totally the way to do it," then you are correct. You don't strictly need to include the data type unless your database cares about that kind of thing. (MySQL doesn't care, it will magically cast the value. SQLite doesn't care. Postgres might care.)



rivals posted:

Yeah, I checked and $result is false. This is what I get:
code:
query: SELECT * FROM plaintext WHERE username='a' OR 1=1#' AND password='f'
1064: You have an error in your SQL syntax; check the manual that corresponds to 
your MySQL server version for the right syntax to use near 'password='f'' at line 2 
Have you tried putting a space between the # and the 1=1? I'm grasping at straws here, I haven't seen a 3.x version of MySQL in the wild in five years. The 3.x-4.1 documentation suggests you can also try C-style /* */ block comments, though you'd have to combine username/password exploits to pull that off.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Have you tried the tidy extension? Though it seems to kill whitespace, not structure it. Hmm. Alternatively, you could load your output into a DOMDocument using loadHTML() and then manually perform output by crawling the DOM.

Neither of these is likely to be very fast.

McGlockenshire fucked around with this message at 05:41 on Jun 2, 2010

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Rewinding a bit, as I didn't see this addressed.

Hammerite posted:

Should I be checking user input to make sure it is well-formed UTF-8? Is there a builtin function for that? What is the worst-case scenario if I fail to screen for bad UTF-8?
Yes, yes, and hilarious XSS. Someone used broken UTF-7 sequences to make XSS exploits workable on Google for IE.

This is a derived and cleaned up version of what we use on $_GET, $_POST and $_REQUEST at work:
php:
<?
/**
 * Clean an array of null values and corrupt UTF-8 sequences
 * @return array
 **/
    function clean_input_corruption($input) {
        foreach($input as $k => $v) {
            if(is_array($v)) {
                $input[$k] = clean_input_corruption($v);
                continue;
            } // end if
            $input[$k] = iconv('UTF-8', 'UTF-8//IGNORE', str_replace("\r\n", "\n", $v));
            $input[$k] = preg_replace('/\0/', '', $v);
        } // end foreach
        return $input;
    } // end clean_input_corruption?>
The iconv call is what un-breaks broken UTF-8.

This works for us because:
1) We never get input that contains newlines in which we'd want to preserve carriage returns.
2) If the user submits broken UTF-8 to us, we don't care that the default behavior of iconv is to stop on error thus possibly truncating the string at the break.
3) We never get input from users that contains null.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Doctor rear end in a top hat posted:

I need to create xml to send to FedEx and UPS so I can get tracking information. [...] Is there an easy way to generate this XML or am I just going ot have to do it the ugly way?
The ugly way is going to save you plenty of time and effort and is more likely to be pain-free.

If concatenating strings together to form XML gives you the willies, try parsing the XML you've pasted every time you need it, manipulating the bits you need to manipulate with whatever XML library you prefer (SimpleXML may be too simple to deal with namespaces, it's been a while), and then emit the result.

Don't try to store it in some other form. It's far more likely that the underlying library will change how it accepts not-stored-as-XML XML than FedEx's API will change. We've needed to make a grand total of one change to the XML in our shipping code since 2007-ish.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Golbez posted:

Another crazy-rear end question...

Let's say a function returns an array. Is it possible to immediately ask for a value from this array?

This will be possible in the next major version of PHP.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

A hamburger? posted:

After looking through dozens of xml namespace things, I still have no idea how to use them. All I know is that I can parse through regular nodes with $xml->children() but that doesn't work for getting the values of nodes with namespaces, or so it seems.
Sounds like you're using the DOM. The functions that end in "NS" all have to do with namespaces. They'll be helpful.

Unfortunately that's the limit of my knowledge on the matter...

McGlockenshire
Dec 16, 2005

GOLLOCKS!

micropenis posted:

I'm in way over my head here. Basically I'm trying to figure out how to add/replace text before the very first <h3> of a document. I've been told to check out php preg_replace and RegEx. Will these be able to do what I would like?

Normally I'd say "don't parse HTML with regexes!", because you shouldn't parse HTML with regexes. But you aren't parsing, you just need to insert some text that is totally not markup before a tag, right?

$result = preg_replace('/<h3>/', 'Stuff before the tag and also the <h3>', $variable, 1);

The 1 at the end limits it to one replacement. This is untested, you might need to escape the brackets. I'd say you could use str_replace instead, but it doesn't seem to have a mechanism to limit the number of results.




Golbez posted:

This could go in the SQL thread as well, but I had yet another coding theory question: How much to do you do in a MySQL query versus PHP?
[...]
Now, the boss has said, use PHP to cut down on MySQL server load

That's an awful reason. But it should still be done in PHP. You're formatting it for output, right? It's not the database's job to format things for output, that's the job of the thing that will actually perform the output.

e: drat you, Doctor rear end in a top hat!

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Flamadiddle posted:

Also, if this doesn't sound like a sensible way to hold error messages or there's a better way, I'm all ears.

Why are you manually parsing a file into a hash every time instead of just storing it as a hash to begin with and using include?

Alternatives include gettext or storing the text strings in a database of some sort for the ultimate in overkill.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

FeloniousDrunk posted:

Thanks, I always forget about Pear. Now what is this 'auth_token' and 'token_secret' crap... don't answer that, it'll be a fun puzzle for this afternoon.

OAuth is a world of pain and horrors unless you've worked with something that works similarly. I would not describe it as a fun puzzle, especially when all the major libraries have little stupid idiosyncrasies as I recently discovered.

Apparently OAuth 2 (currently a draft) lightens up on the signing bullshit in favor of just requiring the use of SSL. I'm not sure if it still requires four tokens in total.

McGlockenshire fucked around with this message at 23:31 on Sep 2, 2010

McGlockenshire
Dec 16, 2005

GOLLOCKS!

FeloniousDrunk posted:

As for "pain and horrors unless you've worked with something that works similarly", I've worked with Shibboleth.

This one? Well, all the keywords are there, let's see how it --

Shibboleth posted:

Shibboleth generates a SAML 1.1 authentication assertion with a temporary "handle" contained within it.

SAML. I'm sorry, man.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

fletcher posted:

How might I use dbquery() to...

This post and the next few replies discuss this problem directly. I'd advise just walking away, it's not worth the aggravation.

Please, please don't post that code, I like my current sanity level. Maybe if you post it in the Coding Horrors thread instead...

McGlockenshire
Dec 16, 2005

GOLLOCKS!

BondGamer posted:

1) User submits date of event and time zone it is in.
2) Convert that to GMT and store in database.
3) Retrieve from database and display in any time zone I need.

Which database? If you're using PostgreSQL or another database that has a TIMESTAMP WITH TIME ZONE column type, you don't need to do the hoop jumping.

If you're using MySQL or another database that only has a simple DATETIME column type, your best bet is not going out of your way to store in GMT, but to store in whatever the database's default timezone is, which is usually the local time, then storing the desired timezone separately as a timezone name/string, not an offset. (Alternatively, if you want to do the hoop jumping, you can store the time in the database as GMT, but that can get annoying really fast.)

Alternatively, epoch timestamps are GMT by their definition, so you can just store one of those and the desired timezone name/string and avoid the column type mess.

Do not under any circumstances store the offset without the timezone name. It is not always going to be possible to get the actual user intent back from an offset alone, especially when DST goes into effect.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
I'd love to hear the justification behind that one.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Golbez posted:

Refusing to allow objects at all.
This is a dangerous, dangerous sign. The lead is very likely suffering from one or more of a handful of problems.
  1. He has a single, unified vision of where his software is going, and has no intention of allowing external input. This may be true especially if no code gets written without his explicit permission and/or direction.
  2. Worse, he doesn't have a single, unified version of where his software is going, or he has one and is unable to articulate it. This may be true especially if other coders on the project constantly have to ask for guidance or clarification.
  3. He may have first experienced excessive OO wankery, such as a Java framework that requires a dozen layers of indirection to get anything done, and believes that such dangerous levels of obsessive idiocy is what OO actually is.
  4. He may have an irrational distaste for OO PHP. This can frequently come from first learning PHP OO in the PHP4 era and not learning what changed in PHP5. A major hint that this may be the case is if everything is passed by reference, especially at call time or if references are discouraged.
  5. And finally, he may not understand OO and is thus afraid of it. This is the worst possible problem, and is frankly the most likely given that you're still using the mysql extension.
The project I now lead at work was built by someone that matched parts of this profile. You do not want to work under someone like this. It took the entire team threatening to ragequit (and one doing so) and some major pushing from management before he realized the scale of the problem. He quit. You might not be so lucky. (Then again, I'm not so lucky. I'm responsible for maintaining and now replacing this clusterfuck. Hopefully after I'm long gone, my name won't be cursed weekly as his is...)

McGlockenshire fucked around with this message at 06:52 on Sep 11, 2010

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Golbez posted:

It's been his for four years, I might be the first new one, I don't know. There's no other coders but us.
This also explains much. Learning to work as a team is a challenge.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
If you can daemonize your python, and can install software on your machine, take a look at Gearman. There are python and PHP bindings.

It should make it trivial for your PHP code to call defined functions in python-land, without process control, without forking (well, forking PHP), etc.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Here's a throwback to the discussion about database interfaces. Maybe it should be in Coding Horrors instead.

Long story short, I'm fixing our "home-grown" database abstraction interface and am getting ready to send all of the changes upstream to the open source project (and original devs) that wrote it. It's grown from a "let's switch from mysql functions to an object, yay!" to a "hay, what's this mysqli thing guys?" to "gently caress MySQL, gimme Postgres! Oh, and sqlite too." SQLite support is done through PDO, and both PDO and PG do their own proper placeholder thing. After I got those using native placeholders instead of our manual replacement mechanism, I decided to tackle mysqli's prepared statements.

Now, I've always recommended mysqli, because it's mysqli. The I stands for "Improved", right? It's supposed to be better. And it is, in a lot of ways. But I never actually used any of the "improved" methods.

Has anyone actually used mysqli's prepared statements? Who designed this poo poo?
  • You have to -- have to -- specify the data type in the bind. That works fine when you're building each query manually, but when all I've got is a bunch of ?s, it's kind of hard to figure out which exact type each variable is going to be, outside of numbers.
  • You can't pass in an array of values. One at a time only. So, let's loop!
  • The bound variables are passed by loving reference. Holy poo poo, what was the designer smoking? Remember that need to loop over the arguments we got passed because it can't take an array? Yeah, that just broke everything.

What am I talking about? Here, let's look at this code:
php:
<?php
$foo range(1100);
$bar = array();
foreach($foo as $baz)
    $bar[] = &$baz;
print_r($bar);

Quick, what gets printed? If you answered 1 through 100, you are wrong.

PHP references are attached to the container -- the variable itself -- not the value stored in the container. Foreach, the best, fastest way to iterate over an array, reuses $baz in each loop, replacing the value at the start. We just created a list of 100 references to the very last element in $foo.

In order to do this correctly, I need to use an alternative loop structure (very easy, enough to make this a non-complaint), or I need to do a bizarre thing to work around foreach's behavior: foreach($foo as &$baz). See what changed? $baz is a reference there, indicating that I want the values in $foo passed into $baz by reference to begin with, thus making our assignment a reference of a reference. This would be a completely :psyboom: situation for someone that didn't understand the hosed nature of PHP references.

But it doesn't even matter, because the world explodes the instant I try to stick a string where an integer belongs. I guess I'll stick to our ancient placeholder replacement method, and stop recommending mysqli in favor of just advocating PDO.

Shame on you, PHP internals. Shame on you. Especially after you got reamed because internal functions never handle references safely. Hell, you even said you'd go back and fix all the internal functions that take references to fix them to stop this!

Why do you hate me, PHP?

Why can't I quit you?

McGlockenshire fucked around with this message at 06:28 on Sep 14, 2010

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Cadoc posted:

What's different? I do not use the & before $baz.

Right. That creates a reference, simulating how mysqli_stmt_bind_param creates references, demonstrating that using foreach to loop over arguments and passing them to the bind breaks things.

An alternative loop structure or creating the $baz as a reference in the foreach to begin with fixes that problem, but doesn't stop mysqli's designers from suffering from severe mental incapacitation.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Golbez posted:

Is there any drawback to this apart from code clarity? It suddenly occurred to me that it seemed weird to insist on declaring my arrays.

It's a good habit. Here's why:

php:
<?php
$foo = array();
if($bar) {
    while($baz frob())
        $foo[] = $baz->what()
}
foreach($foo as $argh)
    echo "Metasyntactic variables {$argh}, don't they?\n"
Without the initial declaration of $foo as an empty array, if the condition never fires, your foreach will try to iterate over null. That causes a warning.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

quote:

I've never seen this construction anywhere else. Think there's a reason for that?

Yup. Versions prior to 5.4 (aka the current trunk) don't have the ability to dereference an array returned from a function without assigning the array to a variable first. Once you get in that habit, it's easy to forget that you can still provide functions that provide arrays to other functions and language constructs that want arrays.

Between this and traits, I'm really looking forward to 5.4.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Maniaman posted:

Is it a horribly bad idea to use short tags? I've been writing an inhouse app that makes heavy use of <?=$foo;?> as opposed to <?php echo $foo; ?>. I'm not super concerned with portability (its an in-house app) but more concerned with them removing the short tags in a later version.

Short tags are in no danger of deprecation. ASP tags are far more likely to find themselves on the chopping block, but are safe for now.

Even then, a simple global search/replace will fix things right up. "<?=" is just a shortcut for "<?php echo"

McGlockenshire
Dec 16, 2005

GOLLOCKS!

quote:

But there wasn't any, so for shits and giggles I deleted the ?> at the end of the template file. Now it worked, though I had a feeling this could be a very bad PHP practice

Quite the opposite. Excluding the closing tag from the bottom of the file is considered best practice to avoid the whitespace issue. Likewise, making sure that the opening tag is the first thing in the file and making sure your editor isn't inserting a unicode BOM is also best practice. Also consider output buffering.

That being said, mixing PHP and HTML as you're doing can be dangerous and hard to visually parse. Consider adding what might feel like "too much" space to make what's going on more obvious.

Also remember that PHP has heredocs and nowdocs, which are a good alternative to switching in and out of PHP code.

McGlockenshire fucked around with this message at 06:14 on Sep 19, 2010

McGlockenshire
Dec 16, 2005

GOLLOCKS!
I was about to point you at PDOStatement::rowCount(), but it says right there that it doesn't work for SELECTs and you should issue two statements, one with a COUNT(*) and then the real one. Your solution works just as well for MySQL, just be aware that unbuffered queries can bite you in the rear end when working with prepared statements and having multiple statement handles open at once. You may have to use PDO::MYSQL_ATTR_USE_BUFFERED_QUERY.

Out of curiosity, why do you need the result count ahead of time if you're iterating over them blindly?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Doctor rear end in a top hat posted:

In other words, you're telling me to store the results data in an array/object and then go through that for the output.

Exactly. However, PDO doesn't always make it easy. There's no one-step method to prepare a statement and execute it. There's only just blind execution without placeholders. Then again, you're already working without them if you're stuck on the old mysql extension.

It's not uncommon to create class that extends PDO and includes convenience methods to work around this problem.

Also,

Doctor rear end in a top hat posted:

one of our machines is running an older version of MySQL and mysqli won't work on it. (no subqueries, either)
Holy poo poo, that means you're still running 3.x. 3.23.58 was released seven years ago last week, and all support options ended at the end of 2006. Further, they've stated that the old version manuals may be removed after the end of this year. Maybe this might be enough ammo to convince whoever needs convincing to dedicate whatever resources are needed to get things running on something more modern?

McGlockenshire
Dec 16, 2005

GOLLOCKS!
FYI, you can also pass an array into execute rather than doing each bind on it's own.

Adbot
ADBOT LOVES YOU

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Getters/setters: Avoid. You either have to write them all yourself manually or dick around with the visibility of the property and use __get/__set. Not worth it now.

For your User class, putting in static methods to retrieve relevant data might make the class feel cluttered. Consider creating a class that handles those tasks on it's own, and can also be responsible for fetching User instances. So, $users = UserManager::list() and $user = UserManager::retrieve($id). Errors on the latter can just return null.

There's a pattern name for this process, but it escapes me. The general theme is that classes should do one thing. The class named User should deal with one user. If you need to work with multiple users, you probably shouldn't wedge that functionality into the User class.

This only works well for certain types of data.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply