¿Cuál es tu estilo de codificación?
- UPSGuy
- Lurker ಠ_ಠ


- Registrado: Jul 25, 2005
- Mensajes: 2735
- Loc: Nashville, TN
- Status: Offline
¿Es usted el tipo de comentario completo? no comments? todo con pestañas en su lugar? Condensada de lo posible?
¿Cuáles son esas reglas que usted no puede vivir sin él?
¿Cuáles son esas manías que acaba de odio a encontrar en el código de otra que mas?
Im curiosidad por ver que el populus Ozzu general cae
¿Cuáles son esas reglas que usted no puede vivir sin él?
¿Cuáles son esas manías que acaba de odio a encontrar en el código de otra que mas?
Im curiosidad por ver que el populus Ozzu general cae
I'd love to change the world, but they won't give me the source code.
- Anonymous
- Bot


- Registrado: 25 Feb 2008
- Mensajes: ?
- Loc: Ozzuland
- Status: Online
Septiembre 28th, 2009, 11:22 am
- joebert
- Sledgehammer


- Registrado: Feb 10, 2004
- Mensajes: 13455
- Loc: Florida
- Status: Offline
Me gusta llaves en sus propias líneas.
Me gusta! (no) tener espacios en ambos lados.
No me gustan las clases singleton que buscar instancias de sí mismos dentro de un constructor.
No me gusta basados en el espacio sangría, me gusta aquí.
Me gustan los argumentos a favor de cosas como printf estar en sus propias líneas y sangría. Me gustan los comentarios con el argumento número colocado de forma periódica.
No me gusta cuando un número simbólico están disponibles para las funciones de estilo printf y no se usan, no importa cuán pocos argumentos hay ningún argumento o si se reutilizan en la máscara. No puedo recordar cuántas veces Ive tenía que volver y la modificación de un llamada a printf, cuando un argumento se agrega más adelante.
No me gustan los comentarios que se parecen a la documentación. Si el comentario empieza a tomar la mitad de los editores de su pantalla no es un comentario Freakin, crear una página de documentación maldita y reemplazar cuál es el código con un enlace a dicha página ya. No quiero oír mierda de empresa que sea de alojamiento, que no necesita alojamiento para incluir una carpeta de documentos en el paquete que puede enlazar.
No me gustan los múltiples comentarios en línea como ésta cuando haya un real de múltiples sintaxis de comentario de línea disponible.
No me gustan los comentarios que se parecen a la documentación. Sí, esto vale la pena mencionar dos veces.
No me gusta el espacio entre el cierre de pare nothesis. Puedo tratar con los espacios después de la llamada primera función.
Me gusta comillas cuando importa.
Me gusta esta
No me gusta este
Pero me gusta esta
Eso es una cuestión de cómo funciona mi resaltador de sintaxis.
Eso es todo lo que viene a la mente en este momento.
Código: [ Select ]
if(...)
{
}
{
}
- if(...)
- {
- }
Me gusta! (no) tener espacios en ambos lados.
Código: [ Select ]
if( ! something)
if(something)
if(something)
- if( ! something)
- if(something)
No me gustan las clases singleton que buscar instancias de sí mismos dentro de un constructor.
No me gusta basados en el espacio sangría, me gusta aquí.
Me gustan los argumentos a favor de cosas como printf estar en sus propias líneas y sangría. Me gustan los comentarios con el argumento número colocado de forma periódica.
Código: [ Select ]
printf(
'This %2$s how %1$s like it',
who,
whether // %2$s
);
'This %2$s how %1$s like it',
who,
whether // %2$s
);
- printf(
- 'This %2$s how %1$s like it',
- who,
- whether // %2$s
- );
No me gusta cuando un número simbólico están disponibles para las funciones de estilo printf y no se usan, no importa cuán pocos argumentos hay ningún argumento o si se reutilizan en la máscara. No puedo recordar cuántas veces Ive tenía que volver y la modificación de un llamada a printf, cuando un argumento se agrega más adelante.
No me gustan los comentarios que se parecen a la documentación. Si el comentario empieza a tomar la mitad de los editores de su pantalla no es un comentario Freakin, crear una página de documentación maldita y reemplazar cuál es el código con un enlace a dicha página ya. No quiero oír mierda de empresa que sea de alojamiento, que no necesita alojamiento para incluir una carpeta de documentos en el paquete que puede enlazar.
No me gustan los múltiples comentarios en línea como ésta cuando haya un real de múltiples sintaxis de comentario de línea disponible.
Código: [ Select ]
// one
// two
// three
// two
// three
- // one
- // two
- // three
No me gustan los comentarios que se parecen a la documentación. Sí, esto vale la pena mencionar dos veces.
No me gusta el espacio entre el cierre de pare nothesis. Puedo tratar con los espacios después de la llamada primera función.
Código: [ Select ]
if(something( something2( something2())))
Me gusta comillas cuando importa.
Código: [ Select ]
$var = "My name is $name";
$var = 'My name is ' . $name;
$var = 'My name is ' . $name;
- $var = "My name is $name";
- $var = 'My name is ' . $name;
Me gusta esta
Código: [ Select ]
$var = "My name is {$obj->name}";
No me gusta este
Código: [ Select ]
$var = "My name is $obj->name";
Pero me gusta esta
Código: [ Select ]
$var = "My name is $name";
Eso es una cuestión de cómo funciona mi resaltador de sintaxis.
Eso es todo lo que viene a la mente en este momento.
Strong with this one, the sudo is.
- Bogey
- Bogey


- Registrado: Jul 14, 2005
- Mensajes: 8211
- Loc: USA
- Status: Offline
Podría ser más fácil si te muestro una pieza ejemplo de mi código y le mostraremos cómo hacerlo:
Supongo que podría tratar de explicar rápidamente, así...
Soy un maníaco comentario...Me acaba de comentar acerca de cada línea de código para explicar lo que estoy haciendo. Puedo añadir en pequeños recordatorios y notas, los créditos si soy lo que es público, el primer comentario es el nombre del archivo y el archivo de descripción.
Me gusta usar las variables y los nombres de las clases que describe lo que se están manteniendo o función tanto como sea posible con la menor cantidad de palabras posibles...
Yo todo lo que guión y mantener todo en línea con lo que se asocian a...thats la mejor manera que podía explicar eso.
Soy una perfeccionista, por lo que si puedo copiar una clase de alguien, no importa lo grande que es, en mi comentario todo y todo guión que como deseo, antes de subirlo a mi sitio
Yo también aborrezco:
\
Lo que me gusta es:
Me gusta usar las llaves dentro de comillas dobles para acceder a objetos y las matrices. Me gusta usar comillas dobles, y punto.
PHP Código: [ Select ]
<?php
/*
* install.php
* A global installation class created to be used with any kind of application.
*
* Before doing anything with this class, I recommend you read the documentation to figure out
* what you are doing. That's so you won't accidentally mess something up.
*/
class install {
/*
* The stages that the script would have in it's overall installation process.
* This is to ensure that the user wouldn't just put anything random into the
* url and try to do something. Also for automation.
*/
var $stages = array('stage_1','stage_2','stage_3');
/*
* This determines if we would have anything to do with SQL
*/
var $use_sql = true;
/*
* This would store the SQL information once/if recieved (For the stage submitted on... later on, uses $_SESSION)
*/
var $sql = array('HOST' => null, // MySQL Host
'USER' => null, // MySQL Username
'PASS' => null, // MySQL Passowrd
'DBASE' => null, // MySQL Database Name
'TBL_PRE' => null); // MySQL Table Prefix
/*
* Determines if a global file would be created at the end.
*
* The global file would consist of the MySQL host, username, password and the database name
*/
var $create_global = true;
/*
* Determines the location that the configuration file would be saved to (Make sure it exists)
*/
var $gl_loc = 'includes/';
/*
* Determines the name for the global file
*/
var $globals = 'global';
/*
* Determines the global file type (also used as the extension for the global file)
*
* Possible types:
* XML, PHP
*
* NOTE: If you know PHP it would be easy for you to add more types here
*/
var $global_type = 'XML';
/*
* Set to true if you are installing and want to check if the application is already installed.
*
* If the global file exists, than the application is installed. Otherwise the application is not installed.
*/
var $check_installed = true;
/*
* location where the forms are located (Set the filename equal to their stage)
*/
var $forms = 'forms/';
/*
* Location of the SQL file holding the SQL queries to be made
*
* NOTE:
* Make sure that every CREATE query is set into an array called $create even if there is only one query.
* Make sure that every INSERT query is set into an array called $insert even if there is only one query.
*/
var $sqls = 'sql/queries.php';
/*
* The following forces the class to die on error and print the error
*/
var $force_errors = false;
/*
* Set the following true if you want the script to debug at each error
*/
var $debug = true;
/*
* Determines weather you want a HEADER redirect or one by JavaScript
*
* Possible values:
* HEADER (PHP Header redirection)
* JavaScript (Javascript Window redirection)
*/
var $redirect_type = 'JavaScript';
/*
* Redirection place where users would go to upon finishing installation
*/
var $redirect_loc = 'documentation.html';
/*
* The following variables are variables for this class. Configure them at your own risk
*/
var $error = array(); // Silent errors returned by this class
var $errno = 0; // Number of errors generated by the class
var $global_loc = null; // The location of the global file created
/*
* function __construct( VOID )
*
* Function that basically sets certain variables.
*/
function __construct()
{
// Creating the location where the global file would be and it's name with extension type
$this->global_loc = $this->gl_loc . $this->globals . '.' . strtolower($this->global_type);
}
/*
* function setup( [ string $stage ] )
* @string $stage - The current stage of the installation. (Includes the form)
*
* Includes the form for the current setup stage
*/
function setup()
{
// Making sure we've got the right stage
$stage = (!isset($_GET['stage'])) ? $this->stages[0] : $_GET['stage'];
// Including the corrent stage's form
include_once($this->forms . $stage . '.php');
}
/*
* function cont( VOID )
*
* Checks the current stage and determines what the next stage should be
*/
function cont()
{
// Getting the current stage the user is on
$stage = (!isset($_GET['stage'])) ? $this->stages[0] : $_GET['stage'];
// Advancing to the next stage
$stage = $this->advance($stage);
// Checking if the installation process was finished
if($stage == sizeof($this->stages) || $stage == false)
{
// Checking if we need to create the global file
if($this->create_global == true)
{
$this->create_global();
}
else
{
/*
* The redirect type here is set to JavaScript to over-ride HEADER.
* Reason being, is when the installation is done and the script
* is supposed to redirect the user to the page you specified,
* then the HEADER tries to look for a class that isn't there,
* but JavaScript does it correctly. Don't know why.
*/
$this->redirect_type = "JavaScript";
// Redirecting the user to the page you specified
$this->redirect($this->redirect_loc);
}
break;
}
// Getting the page the user is on (The installation page)
$page = $_SERVER['PHP_SELF'];
// Redirecting the user to the next stage
$this->redirect("{$page}?stage={$this->stages[$stage]}");
}
/*
* function advance( string $stage )
* @string $stage - Current stage that the function would determine the next from
*
* Redirects the user to the next stage after one is done
*/
function advance($stage)
{
// Going through the stages array and looking for the current stage
foreach($this->stages as $id => $st)
{
// Adding 1 to the current stage key
if($stage == $st)
{
return $id + 1;
}
}
// Getting the amount of stages there are
$stage_size = sizeof($this->stages);
// Checking if this is the last stage or if the stage doesn't exist
if($id == $stage_size)
{
return false;
}
else
{
// Neither found... we don't need to advance since the installation is done!
$this->error('STAGE_ADVANCE', "An unknown error occured in " . (__FILE__) . ' - (<strong>' . (__LINE__) . '</strong>)');
return $id;
}
}
/*
* function set_sql( string $host, string $user, string $pass, string $dbname, string $tbl_pre )
* @string $host - The MySQL Host
* @string $user - The MySQL User
* @string $pass - The MySQL Password
* @string $dbname - The Database Name
* @string $tbl_pre - The MySQL Table Prefix
*
* Function that sets the class sql array to their appropriate values
*/
function set_sql($host, $user, $pass, $dbname, $tbl_pre)
{
// Setting the SQL array to it's appropriate values
$this->sql = array('HOST' => $host,
'USER' => $user,
'PASS' => $pass,
'DBASE' => $dbname,
'TBL_PRE' => $tbl_pre);
// Setting the SQL session
$_SESSION['sql'] = $this->sql;
// Checking if the values submitted were valid
if($this->check_sql($host, $user, $pass, $dbname) == true)
{
// Values were correct
return true;
}
// Values were incorrect
$this->error('SETTING_SQL', "Values submitted weren't valid");
return false;
}
/*
* function create_global( VOID )
*
* Function that creates the global file.
*/
function create_global()
{
// Checking if we need to check if the application is already installed
if($this->check_installed == true)
{
// Checking if the global file exists
if(file_exists($this->global_loc) == true)
{
// Killing script execution with an error
$this->error('APP_INSTALLATION', "Application already installed.");
}
}
// Checking what kind of global file it would be... PHP or XML
switch($this->global_type)
{
case 'XML':
// The XML content
$content = <<<EOT
<?xml version="1.0" encoding="ISO-8859-1"?>
<database>
<host>{$_SESSION['sql']['HOST']}</host>
<user>{$_SESSION['sql']['USER']}</user>
<pass>{$_SESSION['sql']['PASS']}</pass>
<dbname>{$_SESSION['sql']['DBASE']}</dbname>
<table_prefix>{$_SESSION['sql']['TBL_PRE']}</table_prefix>
</database>
EOT;
break;
case 'PHP':
// The PHP content
$content = <<<EOT
<?php
/* The global configuration file */
// The MySQL Host
$host = "{$_SESSION['sql']['HOST']}";
// The MySQL User
$user = "{$_SESSION['sql']['USER']}";
// The MySQL password
$pass = "{$_SESSION['sql']['PASS']}";
// The MySQL Database Name
$dbname = "{$_SESSION['sql']['DBASE']}";
// The MySQL Table Prefix
$tbl_pre = "{$_SESSION['sql']['TBL_PRE']}";
?>
EOT;
break;
default:
// Neither of the correct options were given. Defaulting to XML
$this->global_type = 'XML';
$this->create_global();
break;
}
// Creating the Global File
if(touch($this->global_loc) != false)
{
// Putting the contents into the global file
if(file_put_contents($this->global_loc, $content) != false)
{
// Checking if we are to create SQL tables into the created database
if($this->use_sql == true)
{
// Doing the SQL portion of the installation
$this->do_sql();
}
else
{
// Redirecting the user to the finish page
$this->redirect($this->redirect_loc);
}
}
}
else
{
// The contents weren't put into the global file. Set the error and return false
$this->error('GLOBAL_FILE_CONTENT', "Contents were failed to be put into the global file {$this->global_loc}");
return false;
}
}
/*
* function do_sql( VOID )
*
* Function that carries out the available SQL queries provided in the SQL file
*/
function do_sql()
{
// Requiring the SQLs page
require $this->sqls;
// Connecting to MySQL
$link = mysql_connect($_SESSION['sql']['HOST'], $_SESSION['sql']['USER'], $_SESSION['sql']['PASS']) or die(mysql_error());
// Selecting the database
$db = mysql_select_db($_SESSION['sql']['DBASE']) or die(mysql_error());
// Checking if CREATE array exists
if(isset($create))
{
// Doing the SQL table creation
foreach($create as $query)
{
// executing the create queries
$result = mysql_query($query, $link);
// Checking of one of the queries failed
if($result == false)
{
$this->error('SQL_QUERY_CREATE',"The SQL query ({$query}) failed to execute: MySQL Returned '" . mysql_error() . "'");
return false;
break;
}
}
}
// Checking if INSERT array exists
if(isset($insert))
{
// Looping through each insert query and doing them
foreach($insert as $query)
{
// Executing the queries
$result = mysql_query($query, $link);
// Checking if one of them failed.
if($result == false)
{
$this->error('SQL_QUERY_INSERT',"The SQL query ({$query}) failed to execute: MySQL Returned '" . mysql_error() . "'");
return false;
break;
}
}
}
// Making sure there were no possible errors
if(!isset($create) && !isset($insert))
{
$this->error('DO_SQL_EXECUTION',"The SQL file provided doesn't have the required arrays set.");
return false;
}
// Everything carried out correctly. Redirect to the homepage
$this->redirect($this->redirect_loc);
}
function redirect($page)
{
// Redirecting the user to the next stage based on the preferable redirection type
switch($this->redirect_type)
{
case "HEADER":
// It's header... turning the output buffering on
ob_start();
// Redirecting the user
header("LOCATION: {$page}");
// Sending the content and turning the output buffer off
ob_end_flush();
break;
case "JavaScript":
// Redirecting the user with JavaScript
echo "<script language=\"JavaScript\">window.location=\"{$page}\";</script>";
break;
default:
// Not one possible redirection type is given... using JavaScript by default
$this->redirect_type = 'JavaScript';
$this->redirect($page);
break;
}
}
/*
* function error( string $key, string $msg )
* @string $key - The key to the error array
* @string $msg - The message to the error array associated to the given $key
*
* Sets the error array and checks on farther error/debugging options
*/
function error($key, $msg)
{
// Setting the error array
$this->error[$key] = $msg;
// Incrementing the error number value
$this->errno += 1;
// Checking if we should debug the error(s)
if($this->debug == true)
{
echo $this->debug();
// Checking if we have to force this error
if($this->force_errors == true)
{
exit;
}
}
// Checking if we should force the error to be shown
if($this->force_errors == true)
{
die("<strong>$key</strong> $msg");
}
}
/*
* function debug( VOID )
*
* Function that does some debugging options on produced/generated errors
*/
function debug()
{
// Going through each error recieved and generating the rest of the debugging text
$err_name = array_keys($this->error);
$err_msg = $this->retaval($this->error, $this->errno - 1, false, true);
$text = "<p><strong>{$err_name[$this->errno - 1]}</strong>: $err_msg<br />\n";
// Finishing off the debugging text
$text .= "</p>";
// Returning the generated text
return $text;
}
/************************************************************************************************
* The following functions are a functions repository *
* To what you may need for the installation *
* process. *
************************************************************************************************/
/*
* function check_sql( [ string $db ] )
* @string $db - Whether or not we should check the validicy of the database
*
* Checks if the MySQL credentials are correct
*/
function check_sql($db = true)
{
// Connecting to MySQL and capturing the resource handler
$link = @mysql_connect($this->sql['HOST'], $this->sql['USER'], $this->sql['PASS']);
// Checking if we are not connected
if($link == false)
{
$this->error('SQL_CONNECTION', mysql_errno() . ' - ' . mysql_error());
}
// Checking if we should select the database
if($db == true)
{
// Selecting the database and capturing the resource handler
$db = @mysql_select_db($this->sql['DBASE']);
// Checking if there were any errors in the connection
if($db == false)
{
$this->error('SQL_DB_SELECT', mysql_errno() . ' - ' . mysql_error());
}
}
// Closing the MySQL Connection if we are connected
if($link != false)
{
@mysql_close($link);
}
// Returning the result.
return (($link != false || $db != false) ? true : false);
}
/*
* function get_xml( string $what )
* @string $what - The variable to take from an XML File
*
* Retrieves a variable from the global file
*/
function get_xml($what)
{
// Loading the global XML file
$db = (array) simplexml_load_file($this->global_file);
// Returing the requested variable to the user
return (string) $db[$what];
}
/*
* function add( string $value [, mix $key] )
* @string $value - The value to add to the additional variable
* @mix $key - This variable could be set to the following possible values
* * 00 (2 zeros) - If you want a numeric, automatically-set keys
* * Anything else - If the key is not set to 00, then the key would be what you put it. (string value and key only)
*
* Creates an additional array for whatever needs you may need.
*/
function add($value, $key = 00)
{
// Checking if the key should be numeric
if($key == 00)
{
// Getting the next available numeric key so we wouldn't over ride a value
foreach($this->add as $id => $val)
{
// Checking if the key is numeric
if(is_numeric($id))
{
$keyed = $id;
}
}
// Incrementing the last numeric key by one
$key = $keyed + 1;
// Unsetting the useless $val
unset($val);
}
// Generating the session
$_SESSION['ADD'][$key] = $value;
// Returning true
return true;
}
/*
* function retaval( array $var, int $akey [, boolean $array [, boolean $value [, boolean $numeric]]])
* @array $var - The array to retrieve the value/key from
* @integer $akey - The key/value to retrieve in numeric terms (1, 2...)
* @boolean $array - Determines if the result should come as an array with the key and the
value.
* @boolean $value - Set true if you want the value, set false if you want the key...
* set to null if you want an array returned with the key and value
* @boolean $numeric - Set to true if you want the key to be numeric... otherwise set
* to false if you want the key to be what it previously was
*
* A function to retrieve a value/key from an array. Returns a string by default, or an
* array if you need the key to be numeric
*
*/
function retaval($var, $akey, $array = false, $value = false, $numeric = false)
{
// Setting some variables
$i = 0;
$num = count($var);
// Looping though the array and choosing the key/value that was asked for
foreach($var as $key => $val)
{
// Setting the return value to the current key/value
if($array == false)
{
$return = (($value == false) ? $key : $val);
}
// Checking if we need the result as an array or a string
if($array != false)
{
// Setting the key to be whatever it needs to be
$key = (($numeric == false) ? $key : 0);
// Setting the return array to be whatever it was meant to be
$return[$key] = (($value == false) ? ((is_null($value)) ? $value : $key) : $val);
}
// Making sure we stop when we have the correct key/value
if($i == $akey)
{
break;
}
// Incrementing the counter
++$i;
}
// Returning the return value if there is any
return (($i > $num) ? false : $return);
}
}
?>
/*
* install.php
* A global installation class created to be used with any kind of application.
*
* Before doing anything with this class, I recommend you read the documentation to figure out
* what you are doing. That's so you won't accidentally mess something up.
*/
class install {
/*
* The stages that the script would have in it's overall installation process.
* This is to ensure that the user wouldn't just put anything random into the
* url and try to do something. Also for automation.
*/
var $stages = array('stage_1','stage_2','stage_3');
/*
* This determines if we would have anything to do with SQL
*/
var $use_sql = true;
/*
* This would store the SQL information once/if recieved (For the stage submitted on... later on, uses $_SESSION)
*/
var $sql = array('HOST' => null, // MySQL Host
'USER' => null, // MySQL Username
'PASS' => null, // MySQL Passowrd
'DBASE' => null, // MySQL Database Name
'TBL_PRE' => null); // MySQL Table Prefix
/*
* Determines if a global file would be created at the end.
*
* The global file would consist of the MySQL host, username, password and the database name
*/
var $create_global = true;
/*
* Determines the location that the configuration file would be saved to (Make sure it exists)
*/
var $gl_loc = 'includes/';
/*
* Determines the name for the global file
*/
var $globals = 'global';
/*
* Determines the global file type (also used as the extension for the global file)
*
* Possible types:
* XML, PHP
*
* NOTE: If you know PHP it would be easy for you to add more types here
*/
var $global_type = 'XML';
/*
* Set to true if you are installing and want to check if the application is already installed.
*
* If the global file exists, than the application is installed. Otherwise the application is not installed.
*/
var $check_installed = true;
/*
* location where the forms are located (Set the filename equal to their stage)
*/
var $forms = 'forms/';
/*
* Location of the SQL file holding the SQL queries to be made
*
* NOTE:
* Make sure that every CREATE query is set into an array called $create even if there is only one query.
* Make sure that every INSERT query is set into an array called $insert even if there is only one query.
*/
var $sqls = 'sql/queries.php';
/*
* The following forces the class to die on error and print the error
*/
var $force_errors = false;
/*
* Set the following true if you want the script to debug at each error
*/
var $debug = true;
/*
* Determines weather you want a HEADER redirect or one by JavaScript
*
* Possible values:
* HEADER (PHP Header redirection)
* JavaScript (Javascript Window redirection)
*/
var $redirect_type = 'JavaScript';
/*
* Redirection place where users would go to upon finishing installation
*/
var $redirect_loc = 'documentation.html';
/*
* The following variables are variables for this class. Configure them at your own risk
*/
var $error = array(); // Silent errors returned by this class
var $errno = 0; // Number of errors generated by the class
var $global_loc = null; // The location of the global file created
/*
* function __construct( VOID )
*
* Function that basically sets certain variables.
*/
function __construct()
{
// Creating the location where the global file would be and it's name with extension type
$this->global_loc = $this->gl_loc . $this->globals . '.' . strtolower($this->global_type);
}
/*
* function setup( [ string $stage ] )
* @string $stage - The current stage of the installation. (Includes the form)
*
* Includes the form for the current setup stage
*/
function setup()
{
// Making sure we've got the right stage
$stage = (!isset($_GET['stage'])) ? $this->stages[0] : $_GET['stage'];
// Including the corrent stage's form
include_once($this->forms . $stage . '.php');
}
/*
* function cont( VOID )
*
* Checks the current stage and determines what the next stage should be
*/
function cont()
{
// Getting the current stage the user is on
$stage = (!isset($_GET['stage'])) ? $this->stages[0] : $_GET['stage'];
// Advancing to the next stage
$stage = $this->advance($stage);
// Checking if the installation process was finished
if($stage == sizeof($this->stages) || $stage == false)
{
// Checking if we need to create the global file
if($this->create_global == true)
{
$this->create_global();
}
else
{
/*
* The redirect type here is set to JavaScript to over-ride HEADER.
* Reason being, is when the installation is done and the script
* is supposed to redirect the user to the page you specified,
* then the HEADER tries to look for a class that isn't there,
* but JavaScript does it correctly. Don't know why.
*/
$this->redirect_type = "JavaScript";
// Redirecting the user to the page you specified
$this->redirect($this->redirect_loc);
}
break;
}
// Getting the page the user is on (The installation page)
$page = $_SERVER['PHP_SELF'];
// Redirecting the user to the next stage
$this->redirect("{$page}?stage={$this->stages[$stage]}");
}
/*
* function advance( string $stage )
* @string $stage - Current stage that the function would determine the next from
*
* Redirects the user to the next stage after one is done
*/
function advance($stage)
{
// Going through the stages array and looking for the current stage
foreach($this->stages as $id => $st)
{
// Adding 1 to the current stage key
if($stage == $st)
{
return $id + 1;
}
}
// Getting the amount of stages there are
$stage_size = sizeof($this->stages);
// Checking if this is the last stage or if the stage doesn't exist
if($id == $stage_size)
{
return false;
}
else
{
// Neither found... we don't need to advance since the installation is done!
$this->error('STAGE_ADVANCE', "An unknown error occured in " . (__FILE__) . ' - (<strong>' . (__LINE__) . '</strong>)');
return $id;
}
}
/*
* function set_sql( string $host, string $user, string $pass, string $dbname, string $tbl_pre )
* @string $host - The MySQL Host
* @string $user - The MySQL User
* @string $pass - The MySQL Password
* @string $dbname - The Database Name
* @string $tbl_pre - The MySQL Table Prefix
*
* Function that sets the class sql array to their appropriate values
*/
function set_sql($host, $user, $pass, $dbname, $tbl_pre)
{
// Setting the SQL array to it's appropriate values
$this->sql = array('HOST' => $host,
'USER' => $user,
'PASS' => $pass,
'DBASE' => $dbname,
'TBL_PRE' => $tbl_pre);
// Setting the SQL session
$_SESSION['sql'] = $this->sql;
// Checking if the values submitted were valid
if($this->check_sql($host, $user, $pass, $dbname) == true)
{
// Values were correct
return true;
}
// Values were incorrect
$this->error('SETTING_SQL', "Values submitted weren't valid");
return false;
}
/*
* function create_global( VOID )
*
* Function that creates the global file.
*/
function create_global()
{
// Checking if we need to check if the application is already installed
if($this->check_installed == true)
{
// Checking if the global file exists
if(file_exists($this->global_loc) == true)
{
// Killing script execution with an error
$this->error('APP_INSTALLATION', "Application already installed.");
}
}
// Checking what kind of global file it would be... PHP or XML
switch($this->global_type)
{
case 'XML':
// The XML content
$content = <<<EOT
<?xml version="1.0" encoding="ISO-8859-1"?>
<database>
<host>{$_SESSION['sql']['HOST']}</host>
<user>{$_SESSION['sql']['USER']}</user>
<pass>{$_SESSION['sql']['PASS']}</pass>
<dbname>{$_SESSION['sql']['DBASE']}</dbname>
<table_prefix>{$_SESSION['sql']['TBL_PRE']}</table_prefix>
</database>
EOT;
break;
case 'PHP':
// The PHP content
$content = <<<EOT
<?php
/* The global configuration file */
// The MySQL Host
$host = "{$_SESSION['sql']['HOST']}";
// The MySQL User
$user = "{$_SESSION['sql']['USER']}";
// The MySQL password
$pass = "{$_SESSION['sql']['PASS']}";
// The MySQL Database Name
$dbname = "{$_SESSION['sql']['DBASE']}";
// The MySQL Table Prefix
$tbl_pre = "{$_SESSION['sql']['TBL_PRE']}";
?>
EOT;
break;
default:
// Neither of the correct options were given. Defaulting to XML
$this->global_type = 'XML';
$this->create_global();
break;
}
// Creating the Global File
if(touch($this->global_loc) != false)
{
// Putting the contents into the global file
if(file_put_contents($this->global_loc, $content) != false)
{
// Checking if we are to create SQL tables into the created database
if($this->use_sql == true)
{
// Doing the SQL portion of the installation
$this->do_sql();
}
else
{
// Redirecting the user to the finish page
$this->redirect($this->redirect_loc);
}
}
}
else
{
// The contents weren't put into the global file. Set the error and return false
$this->error('GLOBAL_FILE_CONTENT', "Contents were failed to be put into the global file {$this->global_loc}");
return false;
}
}
/*
* function do_sql( VOID )
*
* Function that carries out the available SQL queries provided in the SQL file
*/
function do_sql()
{
// Requiring the SQLs page
require $this->sqls;
// Connecting to MySQL
$link = mysql_connect($_SESSION['sql']['HOST'], $_SESSION['sql']['USER'], $_SESSION['sql']['PASS']) or die(mysql_error());
// Selecting the database
$db = mysql_select_db($_SESSION['sql']['DBASE']) or die(mysql_error());
// Checking if CREATE array exists
if(isset($create))
{
// Doing the SQL table creation
foreach($create as $query)
{
// executing the create queries
$result = mysql_query($query, $link);
// Checking of one of the queries failed
if($result == false)
{
$this->error('SQL_QUERY_CREATE',"The SQL query ({$query}) failed to execute: MySQL Returned '" . mysql_error() . "'");
return false;
break;
}
}
}
// Checking if INSERT array exists
if(isset($insert))
{
// Looping through each insert query and doing them
foreach($insert as $query)
{
// Executing the queries
$result = mysql_query($query, $link);
// Checking if one of them failed.
if($result == false)
{
$this->error('SQL_QUERY_INSERT',"The SQL query ({$query}) failed to execute: MySQL Returned '" . mysql_error() . "'");
return false;
break;
}
}
}
// Making sure there were no possible errors
if(!isset($create) && !isset($insert))
{
$this->error('DO_SQL_EXECUTION',"The SQL file provided doesn't have the required arrays set.");
return false;
}
// Everything carried out correctly. Redirect to the homepage
$this->redirect($this->redirect_loc);
}
function redirect($page)
{
// Redirecting the user to the next stage based on the preferable redirection type
switch($this->redirect_type)
{
case "HEADER":
// It's header... turning the output buffering on
ob_start();
// Redirecting the user
header("LOCATION: {$page}");
// Sending the content and turning the output buffer off
ob_end_flush();
break;
case "JavaScript":
// Redirecting the user with JavaScript
echo "<script language=\"JavaScript\">window.location=\"{$page}\";</script>";
break;
default:
// Not one possible redirection type is given... using JavaScript by default
$this->redirect_type = 'JavaScript';
$this->redirect($page);
break;
}
}
/*
* function error( string $key, string $msg )
* @string $key - The key to the error array
* @string $msg - The message to the error array associated to the given $key
*
* Sets the error array and checks on farther error/debugging options
*/
function error($key, $msg)
{
// Setting the error array
$this->error[$key] = $msg;
// Incrementing the error number value
$this->errno += 1;
// Checking if we should debug the error(s)
if($this->debug == true)
{
echo $this->debug();
// Checking if we have to force this error
if($this->force_errors == true)
{
exit;
}
}
// Checking if we should force the error to be shown
if($this->force_errors == true)
{
die("<strong>$key</strong> $msg");
}
}
/*
* function debug( VOID )
*
* Function that does some debugging options on produced/generated errors
*/
function debug()
{
// Going through each error recieved and generating the rest of the debugging text
$err_name = array_keys($this->error);
$err_msg = $this->retaval($this->error, $this->errno - 1, false, true);
$text = "<p><strong>{$err_name[$this->errno - 1]}</strong>: $err_msg<br />\n";
// Finishing off the debugging text
$text .= "</p>";
// Returning the generated text
return $text;
}
/************************************************************************************************
* The following functions are a functions repository *
* To what you may need for the installation *
* process. *
************************************************************************************************/
/*
* function check_sql( [ string $db ] )
* @string $db - Whether or not we should check the validicy of the database
*
* Checks if the MySQL credentials are correct
*/
function check_sql($db = true)
{
// Connecting to MySQL and capturing the resource handler
$link = @mysql_connect($this->sql['HOST'], $this->sql['USER'], $this->sql['PASS']);
// Checking if we are not connected
if($link == false)
{
$this->error('SQL_CONNECTION', mysql_errno() . ' - ' . mysql_error());
}
// Checking if we should select the database
if($db == true)
{
// Selecting the database and capturing the resource handler
$db = @mysql_select_db($this->sql['DBASE']);
// Checking if there were any errors in the connection
if($db == false)
{
$this->error('SQL_DB_SELECT', mysql_errno() . ' - ' . mysql_error());
}
}
// Closing the MySQL Connection if we are connected
if($link != false)
{
@mysql_close($link);
}
// Returning the result.
return (($link != false || $db != false) ? true : false);
}
/*
* function get_xml( string $what )
* @string $what - The variable to take from an XML File
*
* Retrieves a variable from the global file
*/
function get_xml($what)
{
// Loading the global XML file
$db = (array) simplexml_load_file($this->global_file);
// Returing the requested variable to the user
return (string) $db[$what];
}
/*
* function add( string $value [, mix $key] )
* @string $value - The value to add to the additional variable
* @mix $key - This variable could be set to the following possible values
* * 00 (2 zeros) - If you want a numeric, automatically-set keys
* * Anything else - If the key is not set to 00, then the key would be what you put it. (string value and key only)
*
* Creates an additional array for whatever needs you may need.
*/
function add($value, $key = 00)
{
// Checking if the key should be numeric
if($key == 00)
{
// Getting the next available numeric key so we wouldn't over ride a value
foreach($this->add as $id => $val)
{
// Checking if the key is numeric
if(is_numeric($id))
{
$keyed = $id;
}
}
// Incrementing the last numeric key by one
$key = $keyed + 1;
// Unsetting the useless $val
unset($val);
}
// Generating the session
$_SESSION['ADD'][$key] = $value;
// Returning true
return true;
}
/*
* function retaval( array $var, int $akey [, boolean $array [, boolean $value [, boolean $numeric]]])
* @array $var - The array to retrieve the value/key from
* @integer $akey - The key/value to retrieve in numeric terms (1, 2...)
* @boolean $array - Determines if the result should come as an array with the key and the
value.
* @boolean $value - Set true if you want the value, set false if you want the key...
* set to null if you want an array returned with the key and value
* @boolean $numeric - Set to true if you want the key to be numeric... otherwise set
* to false if you want the key to be what it previously was
*
* A function to retrieve a value/key from an array. Returns a string by default, or an
* array if you need the key to be numeric
*
*/
function retaval($var, $akey, $array = false, $value = false, $numeric = false)
{
// Setting some variables
$i = 0;
$num = count($var);
// Looping though the array and choosing the key/value that was asked for
foreach($var as $key => $val)
{
// Setting the return value to the current key/value
if($array == false)
{
$return = (($value == false) ? $key : $val);
}
// Checking if we need the result as an array or a string
if($array != false)
{
// Setting the key to be whatever it needs to be
$key = (($numeric == false) ? $key : 0);
// Setting the return array to be whatever it was meant to be
$return[$key] = (($value == false) ? ((is_null($value)) ? $value : $key) : $val);
}
// Making sure we stop when we have the correct key/value
if($i == $akey)
{
break;
}
// Incrementing the counter
++$i;
}
// Returning the return value if there is any
return (($i > $num) ? false : $return);
}
}
?>
- <?php
- /*
- * install.php
- * A global installation class created to be used with any kind of application.
- *
- * Before doing anything with this class, I recommend you read the documentation to figure out
- * what you are doing. That's so you won't accidentally mess something up.
- */
- class install {
- /*
- * The stages that the script would have in it's overall installation process.
- * This is to ensure that the user wouldn't just put anything random into the
- * url and try to do something. Also for automation.
- */
- var $stages = array('stage_1','stage_2','stage_3');
- /*
- * This determines if we would have anything to do with SQL
- */
- var $use_sql = true;
- /*
- * This would store the SQL information once/if recieved (For the stage submitted on... later on, uses $_SESSION)
- */
- var $sql = array('HOST' => null, // MySQL Host
- 'USER' => null, // MySQL Username
- 'PASS' => null, // MySQL Passowrd
- 'DBASE' => null, // MySQL Database Name
- 'TBL_PRE' => null); // MySQL Table Prefix
- /*
- * Determines if a global file would be created at the end.
- *
- * The global file would consist of the MySQL host, username, password and the database name
- */
- var $create_global = true;
- /*
- * Determines the location that the configuration file would be saved to (Make sure it exists)
- */
- var $gl_loc = 'includes/';
- /*
- * Determines the name for the global file
- */
- var $globals = 'global';
- /*
- * Determines the global file type (also used as the extension for the global file)
- *
- * Possible types:
- * XML, PHP
- *
- * NOTE: If you know PHP it would be easy for you to add more types here
- */
- var $global_type = 'XML';
- /*
- * Set to true if you are installing and want to check if the application is already installed.
- *
- * If the global file exists, than the application is installed. Otherwise the application is not installed.
- */
- var $check_installed = true;
- /*
- * location where the forms are located (Set the filename equal to their stage)
- */
- var $forms = 'forms/';
- /*
- * Location of the SQL file holding the SQL queries to be made
- *
- * NOTE:
- * Make sure that every CREATE query is set into an array called $create even if there is only one query.
- * Make sure that every INSERT query is set into an array called $insert even if there is only one query.
- */
- var $sqls = 'sql/queries.php';
- /*
- * The following forces the class to die on error and print the error
- */
- var $force_errors = false;
- /*
- * Set the following true if you want the script to debug at each error
- */
- var $debug = true;
- /*
- * Determines weather you want a HEADER redirect or one by JavaScript
- *
- * Possible values:
- * HEADER (PHP Header redirection)
- * JavaScript (Javascript Window redirection)
- */
- var $redirect_type = 'JavaScript';
- /*
- * Redirection place where users would go to upon finishing installation
- */
- var $redirect_loc = 'documentation.html';
- /*
- * The following variables are variables for this class. Configure them at your own risk
- */
- var $error = array(); // Silent errors returned by this class
- var $errno = 0; // Number of errors generated by the class
- var $global_loc = null; // The location of the global file created
- /*
- * function __construct( VOID )
- *
- * Function that basically sets certain variables.
- */
- function __construct()
- {
- // Creating the location where the global file would be and it's name with extension type
- $this->global_loc = $this->gl_loc . $this->globals . '.' . strtolower($this->global_type);
- }
- /*
- * function setup( [ string $stage ] )
- * @string $stage - The current stage of the installation. (Includes the form)
- *
- * Includes the form for the current setup stage
- */
- function setup()
- {
- // Making sure we've got the right stage
- $stage = (!isset($_GET['stage'])) ? $this->stages[0] : $_GET['stage'];
- // Including the corrent stage's form
- include_once($this->forms . $stage . '.php');
- }
- /*
- * function cont( VOID )
- *
- * Checks the current stage and determines what the next stage should be
- */
- function cont()
- {
- // Getting the current stage the user is on
- $stage = (!isset($_GET['stage'])) ? $this->stages[0] : $_GET['stage'];
- // Advancing to the next stage
- $stage = $this->advance($stage);
- // Checking if the installation process was finished
- if($stage == sizeof($this->stages) || $stage == false)
- {
- // Checking if we need to create the global file
- if($this->create_global == true)
- {
- $this->create_global();
- }
- else
- {
- /*
- * The redirect type here is set to JavaScript to over-ride HEADER.
- * Reason being, is when the installation is done and the script
- * is supposed to redirect the user to the page you specified,
- * then the HEADER tries to look for a class that isn't there,
- * but JavaScript does it correctly. Don't know why.
- */
- $this->redirect_type = "JavaScript";
- // Redirecting the user to the page you specified
- $this->redirect($this->redirect_loc);
- }
- break;
- }
- // Getting the page the user is on (The installation page)
- $page = $_SERVER['PHP_SELF'];
- // Redirecting the user to the next stage
- $this->redirect("{$page}?stage={$this->stages[$stage]}");
- }
- /*
- * function advance( string $stage )
- * @string $stage - Current stage that the function would determine the next from
- *
- * Redirects the user to the next stage after one is done
- */
- function advance($stage)
- {
- // Going through the stages array and looking for the current stage
- foreach($this->stages as $id => $st)
- {
- // Adding 1 to the current stage key
- if($stage == $st)
- {
- return $id + 1;
- }
- }
- // Getting the amount of stages there are
- $stage_size = sizeof($this->stages);
- // Checking if this is the last stage or if the stage doesn't exist
- if($id == $stage_size)
- {
- return false;
- }
- else
- {
- // Neither found... we don't need to advance since the installation is done!
- $this->error('STAGE_ADVANCE', "An unknown error occured in " . (__FILE__) . ' - (<strong>' . (__LINE__) . '</strong>)');
- return $id;
- }
- }
- /*
- * function set_sql( string $host, string $user, string $pass, string $dbname, string $tbl_pre )
- * @string $host - The MySQL Host
- * @string $user - The MySQL User
- * @string $pass - The MySQL Password
- * @string $dbname - The Database Name
- * @string $tbl_pre - The MySQL Table Prefix
- *
- * Function that sets the class sql array to their appropriate values
- */
- function set_sql($host, $user, $pass, $dbname, $tbl_pre)
- {
- // Setting the SQL array to it's appropriate values
- $this->sql = array('HOST' => $host,
- 'USER' => $user,
- 'PASS' => $pass,
- 'DBASE' => $dbname,
- 'TBL_PRE' => $tbl_pre);
- // Setting the SQL session
- $_SESSION['sql'] = $this->sql;
- // Checking if the values submitted were valid
- if($this->check_sql($host, $user, $pass, $dbname) == true)
- {
- // Values were correct
- return true;
- }
- // Values were incorrect
- $this->error('SETTING_SQL', "Values submitted weren't valid");
- return false;
- }
- /*
- * function create_global( VOID )
- *
- * Function that creates the global file.
- */
- function create_global()
- {
- // Checking if we need to check if the application is already installed
- if($this->check_installed == true)
- {
- // Checking if the global file exists
- if(file_exists($this->global_loc) == true)
- {
- // Killing script execution with an error
- $this->error('APP_INSTALLATION', "Application already installed.");
- }
- }
- // Checking what kind of global file it would be... PHP or XML
- switch($this->global_type)
- {
- case 'XML':
- // The XML content
- $content = <<<EOT
- <?xml version="1.0" encoding="ISO-8859-1"?>
- <database>
- <host>{$_SESSION['sql']['HOST']}</host>
- <user>{$_SESSION['sql']['USER']}</user>
- <pass>{$_SESSION['sql']['PASS']}</pass>
- <dbname>{$_SESSION['sql']['DBASE']}</dbname>
- <table_prefix>{$_SESSION['sql']['TBL_PRE']}</table_prefix>
- </database>
- EOT;
- break;
- case 'PHP':
- // The PHP content
- $content = <<<EOT
- <?php
- /* The global configuration file */
- // The MySQL Host
- $host = "{$_SESSION['sql']['HOST']}";
- // The MySQL User
- $user = "{$_SESSION['sql']['USER']}";
- // The MySQL password
- $pass = "{$_SESSION['sql']['PASS']}";
- // The MySQL Database Name
- $dbname = "{$_SESSION['sql']['DBASE']}";
- // The MySQL Table Prefix
- $tbl_pre = "{$_SESSION['sql']['TBL_PRE']}";
- ?>
- EOT;
- break;
- default:
- // Neither of the correct options were given. Defaulting to XML
- $this->global_type = 'XML';
- $this->create_global();
- break;
- }
- // Creating the Global File
- if(touch($this->global_loc) != false)
- {
- // Putting the contents into the global file
- if(file_put_contents($this->global_loc, $content) != false)
- {
- // Checking if we are to create SQL tables into the created database
- if($this->use_sql == true)
- {
- // Doing the SQL portion of the installation
- $this->do_sql();
- }
- else
- {
- // Redirecting the user to the finish page
- $this->redirect($this->redirect_loc);
- }
- }
- }
- else
- {
- // The contents weren't put into the global file. Set the error and return false
- $this->error('GLOBAL_FILE_CONTENT', "Contents were failed to be put into the global file {$this->global_loc}");
- return false;
- }
- }
- /*
- * function do_sql( VOID )
- *
- * Function that carries out the available SQL queries provided in the SQL file
- */
- function do_sql()
- {
- // Requiring the SQLs page
- require $this->sqls;
- // Connecting to MySQL
- $link = mysql_connect($_SESSION['sql']['HOST'], $_SESSION['sql']['USER'], $_SESSION['sql']['PASS']) or die(mysql_error());
- // Selecting the database
- $db = mysql_select_db($_SESSION['sql']['DBASE']) or die(mysql_error());
- // Checking if CREATE array exists
- if(isset($create))
- {
- // Doing the SQL table creation
- foreach($create as $query)
- {
- // executing the create queries
- $result = mysql_query($query, $link);
- // Checking of one of the queries failed
- if($result == false)
- {
- $this->error('SQL_QUERY_CREATE',"The SQL query ({$query}) failed to execute: MySQL Returned '" . mysql_error() . "'");
- return false;
- break;
- }
- }
- }
- // Checking if INSERT array exists
- if(isset($insert))
- {
- // Looping through each insert query and doing them
- foreach($insert as $query)
- {
- // Executing the queries
- $result = mysql_query($query, $link);
- // Checking if one of them failed.
- if($result == false)
- {
- $this->error('SQL_QUERY_INSERT',"The SQL query ({$query}) failed to execute: MySQL Returned '" . mysql_error() . "'");
- return false;
- break;
- }
- }
- }
- // Making sure there were no possible errors
- if(!isset($create) && !isset($insert))
- {
- $this->error('DO_SQL_EXECUTION',"The SQL file provided doesn't have the required arrays set.");
- return false;
- }
- // Everything carried out correctly. Redirect to the homepage
- $this->redirect($this->redirect_loc);
- }
- function redirect($page)
- {
- // Redirecting the user to the next stage based on the preferable redirection type
- switch($this->redirect_type)
- {
- case "HEADER":
- // It's header... turning the output buffering on
- ob_start();
- // Redirecting the user
- header("LOCATION: {$page}");
- // Sending the content and turning the output buffer off
- ob_end_flush();
- break;
- case "JavaScript":
- // Redirecting the user with JavaScript
- echo "<script language=\"JavaScript\">window.location=\"{$page}\";</script>";
- break;
- default:
- // Not one possible redirection type is given... using JavaScript by default
- $this->redirect_type = 'JavaScript';
- $this->redirect($page);
- break;
- }
- }
- /*
- * function error( string $key, string $msg )
- * @string $key - The key to the error array
- * @string $msg - The message to the error array associated to the given $key
- *
- * Sets the error array and checks on farther error/debugging options
- */
- function error($key, $msg)
- {
- // Setting the error array
- $this->error[$key] = $msg;
- // Incrementing the error number value
- $this->errno += 1;
- // Checking if we should debug the error(s)
- if($this->debug == true)
- {
- echo $this->debug();
- // Checking if we have to force this error
- if($this->force_errors == true)
- {
- exit;
- }
- }
- // Checking if we should force the error to be shown
- if($this->force_errors == true)
- {
- die("<strong>$key</strong> $msg");
- }
- }
- /*
- * function debug( VOID )
- *
- * Function that does some debugging options on produced/generated errors
- */
- function debug()
- {
- // Going through each error recieved and generating the rest of the debugging text
- $err_name = array_keys($this->error);
- $err_msg = $this->retaval($this->error, $this->errno - 1, false, true);
- $text = "<p><strong>{$err_name[$this->errno - 1]}</strong>: $err_msg<br />\n";
- // Finishing off the debugging text
- $text .= "</p>";
- // Returning the generated text
- return $text;
- }
- /************************************************************************************************
- * The following functions are a functions repository *
- * To what you may need for the installation *
- * process. *
- ************************************************************************************************/
- /*
- * function check_sql( [ string $db ] )
- * @string $db - Whether or not we should check the validicy of the database
- *
- * Checks if the MySQL credentials are correct
- */
- function check_sql($db = true)
- {
- // Connecting to MySQL and capturing the resource handler
- $link = @mysql_connect($this->sql['HOST'], $this->sql['USER'], $this->sql['PASS']);
- // Checking if we are not connected
- if($link == false)
- {
- $this->error('SQL_CONNECTION', mysql_errno() . ' - ' . mysql_error());
- }
- // Checking if we should select the database
- if($db == true)
- {
- // Selecting the database and capturing the resource handler
- $db = @mysql_select_db($this->sql['DBASE']);
- // Checking if there were any errors in the connection
- if($db == false)
- {
- $this->error('SQL_DB_SELECT', mysql_errno() . ' - ' . mysql_error());
- }
- }
- // Closing the MySQL Connection if we are connected
- if($link != false)
- {
- @mysql_close($link);
- }
- // Returning the result.
- return (($link != false || $db != false) ? true : false);
- }
- /*
- * function get_xml( string $what )
- * @string $what - The variable to take from an XML File
- *
- * Retrieves a variable from the global file
- */
- function get_xml($what)
- {
- // Loading the global XML file
- $db = (array) simplexml_load_file($this->global_file);
- // Returing the requested variable to the user
- return (string) $db[$what];
- }
- /*
- * function add( string $value [, mix $key] )
- * @string $value - The value to add to the additional variable
- * @mix $key - This variable could be set to the following possible values
- * * 00 (2 zeros) - If you want a numeric, automatically-set keys
- * * Anything else - If the key is not set to 00, then the key would be what you put it. (string value and key only)
- *
- * Creates an additional array for whatever needs you may need.
- */
- function add($value, $key = 00)
- {
- // Checking if the key should be numeric
- if($key == 00)
- {
- // Getting the next available numeric key so we wouldn't over ride a value
- foreach($this->add as $id => $val)
- {
- // Checking if the key is numeric
- if(is_numeric($id))
- {
- $keyed = $id;
- }
- }
- // Incrementing the last numeric key by one
- $key = $keyed + 1;
- // Unsetting the useless $val
- unset($val);
- }
- // Generating the session
- $_SESSION['ADD'][$key] = $value;
- // Returning true
- return true;
- }
- /*
- * function retaval( array $var, int $akey [, boolean $array [, boolean $value [, boolean $numeric]]])
- * @array $var - The array to retrieve the value/key from
- * @integer $akey - The key/value to retrieve in numeric terms (1, 2...)
- * @boolean $array - Determines if the result should come as an array with the key and the
- value.
- * @boolean $value - Set true if you want the value, set false if you want the key...
- * set to null if you want an array returned with the key and value
- * @boolean $numeric - Set to true if you want the key to be numeric... otherwise set
- * to false if you want the key to be what it previously was
- *
- * A function to retrieve a value/key from an array. Returns a string by default, or an
- * array if you need the key to be numeric
- *
- */
- function retaval($var, $akey, $array = false, $value = false, $numeric = false)
- {
- // Setting some variables
- $i = 0;
- $num = count($var);
- // Looping though the array and choosing the key/value that was asked for
- foreach($var as $key => $val)
- {
- // Setting the return value to the current key/value
- if($array == false)
- {
- $return = (($value == false) ? $key : $val);
- }
- // Checking if we need the result as an array or a string
- if($array != false)
- {
- // Setting the key to be whatever it needs to be
- $key = (($numeric == false) ? $key : 0);
- // Setting the return array to be whatever it was meant to be
- $return[$key] = (($value == false) ? ((is_null($value)) ? $value : $key) : $val);
- }
- // Making sure we stop when we have the correct key/value
- if($i == $akey)
- {
- break;
- }
- // Incrementing the counter
- ++$i;
- }
- // Returning the return value if there is any
- return (($i > $num) ? false : $return);
- }
- }
- ?>
Soy un maníaco comentario...Me acaba de comentar acerca de cada línea de código para explicar lo que estoy haciendo. Puedo añadir en pequeños recordatorios y notas, los créditos si soy lo que es público, el primer comentario es el nombre del archivo y el archivo de descripción.
Me gusta usar las variables y los nombres de las clases que describe lo que se están manteniendo o función tanto como sea posible con la menor cantidad de palabras posibles...
Yo todo lo que guión y mantener todo en línea con lo que se asocian a...thats la mejor manera que podía explicar eso.
Soy una perfeccionista, por lo que si puedo copiar una clase de alguien, no importa lo grande que es, en mi comentario todo y todo guión que como deseo, antes de subirlo a mi sitio
PHP Código: [ Select ]
if ( $something )
Yo también aborrezco:
PHP Código: [ Select ]
if( $something) { /*code*/ }
if ($something) {
//code
}
if($something )
if ($something) {
//code
}
if($something )
- if( $something) { /*code*/ }
- if ($something) {
- //code
- }
- if($something )
Lo que me gusta es:
PHP Código: [ Select ]
if($cause == $effect && $cause2 == $effect2)
{
// Some code
}
else
{
// Some code
}
{
// Some code
}
else
{
// Some code
}
- if($cause == $effect && $cause2 == $effect2)
- {
- // Some code
- }
- else
- {
- // Some code
- }
"Bring forth therefore fruits meet for repentance:" Matthew 3:8
- mk27
- Proficient


- Registrado: Jun 09, 2009
- Mensajes: 334
- Status: Offline
Yo uso el K & R estilo de llaves
, pero estoy obligado a tolerar la Allman (o "todos los espacios en blanco"), como me gusta llamarlo:
La razón no me gusta es que prefiero el código comprimido verticalmente para que pueda ver tanto de él como sea posible a la vez, mientras mantiene el carácter sagrado de la, línea intacta.
Im corto en los comentarios, pero fuerte en la escritura de código claro con las correspondientes nombres de variables. Aborrezco los espacios en el lugar de las pestañas y la idiotez sangría otros.
Otra cosa que también hacen que desea * * todos los demás que es:
Todas las definiciones de funciones en orden alfabético!
A veces voy a incluir un comentario que las listas de llamadas posible, por ejemplo.
ya que este suele ser un indicio importante para mí en cuanto a qué se está encendiendo.
Código: [ Select ]
if (whatever) {
declare this, that;
...
}
declare this, that;
...
}
- if (whatever) {
- declare this, that;
- ...
- }
, pero estoy obligado a tolerar la Allman (o "todos los espacios en blanco"), como me gusta llamarlo:
Código: [ Select ]
sub example
(
arg 1
arg 2
)
{
declare this;
declare that;
wonder if there is a program in here?
}
(
arg 1
arg 2
)
{
declare this;
declare that;
wonder if there is a program in here?
}
- sub example
- (
- arg 1
- arg 2
- )
- {
- declare this;
- declare that;
- wonder if there is a program in here?
- }
La razón no me gusta es que prefiero el código comprimido verticalmente para que pueda ver tanto de él como sea posible a la vez, mientras mantiene el carácter sagrado de la, línea intacta.
Im corto en los comentarios, pero fuerte en la escritura de código claro con las correspondientes nombres de variables. Aborrezco los espacios en el lugar de las pestañas y la idiotez sangría otros.
Otra cosa que también hacen que desea * * todos los demás que es:
Todas las definiciones de funciones en orden alfabético!
A veces voy a incluir un comentario que las listas de llamadas posible, por ejemplo.
Código: [ Select ]
function test() { /* called from etc.html and otherfunc() */
ya que este suele ser un indicio importante para mí en cuanto a qué se está encendiendo.
Página 1 de 1
Para responder a este tema que necesita para ingresar o registrarse. Es gratis.
Publicar Información
- Total de mensajes en este tema: 4 mensajes
- Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 184 invitados
- No puede abrir nuevos temas en este Foro
- No puede responder a temas en este Foro
- No puede editar sus mensajes en este Foro
- No puede borrar sus mensajes en este Foro
- No puede enviar adjuntos en este Foro
