macg-gh / madlibs

A little game that runs on a LAMP stack
0 stars 0 forks source link

Feedback - Classes. #52

Open macg-gh opened 4 years ago

macg-gh commented 4 years ago

So a lot of logic is spread out throughout the files here, so it's tough to understand what everything is doing.

macg-gh commented 4 years ago

From original issue #47 I'll make an example of createtemplate.

./lib/madlib.php:

<? public class Madlib() {

public __construct()
{

}

public GenerateWords($number_of_words)
{
    $output = [];
    if($number_of_words == 0 || $number_of_words > 20)
    {
        throw new Exception("hey too many words");
    }

    for($i = 0; $i < $number_of_words; $i++)
    {
        $output[] = chr(rand(65,90));
    }

    return $output;
}

} ?>

./create_template.php

<? require('./lib/madlib.php');

$madlib = new Madlib();

try
{
    $words = $madlib->GenerateWords($_POST['howmanywords']);
}
catch(Exception $e)
{
    // do something about errors.
}

?> <!DOCTYPE html>

You have selected this many words:
$word) { echo "\n
"; echo $word; echo " :  "; echo "\n
"; echo "\n
"; } ?> Fill in the phrase!



Dump db

This gets better if you have a controller and view where you can separate out some of the logic a bit more, but without getting into that the above is OK. So you'd want to expand on the madlibs class with other logic from pages, and reference that. Generate the dictionary/pspell through there, etc. the constructor method is a magic function which runs when you instantiate the class so if there's setup (i.e. generating the pspell class), it's good to do there. It's optional too so if you don't end up putting anything there you can remove.