Re: [PHP] Try{} Catch()

2008-01-01 Thread Martin Alterisio
2007/12/31, Richard Lynch <[EMAIL PROTECTED]>:
>
> On Sun, December 23, 2007 3:50 pm, Martin Alterisio wrote:
> > It's not supposed to be practical, it's just a way to handle errors.
> > You
> > shouldn't rely on try/catch for algorithm implementation.
> >
> > You create exceptions for errors and unexpected behavior. Then in some
> > other
> > part of the system you use try/catch to prevent the code from
> > terminating
> > abruptly. You catch the exception (you should know which exceptions
> > can be
> > thrown), and act accordingly. Either closing resources, add a log
> > message
> > with debug information, and/or sending an error message to the user.
>
> Except that once you start trying to integrate several large bodies of
> code, you have NO IDEA what exceptions can be thrown, and even less
> idea where they didn't get caught and handled properly.
>
> Worse, many times the library[ies] you are integrating to an abysmal
> job of doing anyting intelligent with the catch block, and you're
> stuck with something even worse than set_error_handler.
>
> try/catch works great for small/medium projects, or even large
> well-documented projects perhaps, but as soon as you start trying to
> integrate several projects...
>
> Well, in MY experience, try/catch just ended up biting me in the butt...
>
> ymmv
> naiaa
> ianal
>
>
You made me realize that I hadn't thought much on the subject. Now I
understand the benefits of how Java integrates exceptions more tightly into
system design. Maybe it would be a good idea to assimilate those features.

The features I'm referring to is the declaration of exceptions thrown by a
function. If you use a function that declares throwing exceptions and don't
use a corresponding try/catch around it, the compile will fail because
you're not handling the exceptions. You can either use a try/catch or
forward the exception by declaring that you will also throw exceptions.

Adding these features to PHP is, I think, not possible (compile-time php
doesn't know what will be the extent of the system at runtime). But you can
use a code analyzer that would parse metadata, such as the one used for
doc-comments, and flag this problems before putting the code into
production.


Re: [PHP] Sayonara PHP

2007-12-28 Thread Martin Alterisio
7;t just bad enough that the RoR developer
failed while doing the first video presentation of RoR. People still kept
boarding that train. And it become worst, people from PHP started to think
that RoR was actually a good idea to be copied.

There are two major faults with RoR:
1) The MVC design pattern is not applied correctly
2) The whole application is designed around the (faulty) MVC design pattern

The MVC design pattern has one purpose and one purpose only, user interface
implementation. RoR forces you to put code that's not pertinent to the
system design because the MVC design pattern is forced on you. You should
never force a problem to fit a pattern.

The resultant is code that's hardly maintainable, mostly redundant, poorly
reusable, scalable only in dreams, and strictly limited.

All the PHP "frameworks" which copied the RoR ideology, had also, most of
the times, copied its faults. Luckily, the Zend Framework was really well
thought, and it is, as I said before, IMHO, the first real php framework.

It's ironic that they choose "Rails" as the name for their abomination. It's
quite appropriate. When you're on rails there's not much you can do, just
one way to go.

The point is... "sayonara PHP" means "sayonara most new clients" right now,
> sayonara "sustained trend", sayonara "all php-based solutions" and
> sayonara
> "most of the web development world". The facts show that googling for
> "PHP"
> throws about 8,830,000,000 results (this is a bit biased, but the point
> still holds)... try to Google for anything else and get similar numbers.


Probably, I'm not sure. But, in this case, yes, I'm saying goodbye to web
development.

[snip]
>
> All in all, my fellow countryman, I guess that unless you have a huge
> positive bank account balance, and you drive a BMW (I don't like them
> anyway…) you'd better off tolerating PHP for this little "namespace issue"
> if you want to stay in business. Unless, of course, that you have an
> incoming contract to develop a core system for an NSA mainframe. And if
> that's the case please tell them I prepare the most awesome "mate"
> (http://en.wikipedia.org/wiki/Mate_(beverage)) in the world, and that you
> cannot work without it.


I'll tell them, but I'm guessing it won't be easy to pass through
immigration with a bag of  "yerba". Last man I heard trying, was almost
body-cavity searched.

xD

I know that, even if you wish to leave PHP forever, you'll come back… all
> the roads will lead you to it. So, you'd better take a smart decision now…
> than have no other choice in the future (... ok, that was kind of The
> Godfather's script, lol).
>
> Enjoy your holidays,
>
> Rob
>

We'll see... for now I'll follow the stupid decision of finally doing what I
intended when I began this whole dance of software development. I hoping
with all my heart that this will go well and I'll never have to work in web
development again. If not, well, I'll come back to whatever it's that's
being used in that specific moment, be it PHP or whatever may come.

Just know that I'm not leaving for some petty reason. And I really hope that
someone else could find anything sensible in the things I posted in the
first mail, and keep on building on top of them.

Best Regards and Happy New Year,

Martin Alterisio


Re: [PHP] Re: [PHP-DEV] Sayonara PHP

2007-12-28 Thread Martin Alterisio
2007/12/26, Colin Guthrie <[EMAIL PROTECTED]>:
>
> Hi,
>
> While I'll admit I've not fully read your mail due to it's relatively
> in-depth and technical nature that I'm not really up-to-speed with
> regarding the internals of PHP, it did strike me when skimming the mail,
> that you've not really covered your personal standpoint now.
>
> You state some interesting technical about how namespaces and such
> will/could work in 5.3 (something which I would personally welcome with
> open arms (especially as I've coded around the autoloading issue with
> other techniques involving regexps of class names and other such
> slightly nasty things (although acceptable if you used good prefixes on
> all your class/interface names)).
>
> But you also say you're leaving PHP (if not for good, at least for now)
> and you don't really say why, other than referring to the hard initial
> entry to the internals community.
>
> If you would be so kind, I think it would be interesting to say why you
> have decided to move away from using PHP (and what you are now intending
> to use!). I think it would help the PHP community grow stronger with
> this kind of information as much as the technical information you've
> already given.


Well, it was my intent not to say that in particular because is rather
personal. I just wanted to pass on all the things that may be of some use to
another developer.

If you must know, there are three reasons why I'm distancing myself from
PHP.

1) I'm tired of web development as a whole. Too many clients which do not
understand what the web is. Too many opiniologists who should know what the
web is but talk about a second web, which is nothing more than the old web
with logos on shiny floor. It feels like the bubble all over again (luckily
I was too young to be affected when the first happened, now I cannot say I
won't be affected).

2) I started in the business of software development with a dream that I was
told afterwards it was childish and immature. Now I've learned enough to
know that my dream, being a game developer, it's neither childish nor
immature, totally the opposite, it's probably the most serious and important
job in the whole software development industry. I wanna give it a try
chasing that rainbow.

3) I'm not so sure anymore if PHP is profitable as a language choice for web
development. The small and medium projects market is becoming infested with
developers who I cannot compete anymore in terms of cost, and software
quality is something this market did not yet got a grasp on. Big projects
market has scalability requirements that aren't easily met on PHP grounds,
and if it does, the cost is code quality or performance, two things that
this market doesn't easily overlook.

Right now, the future of web development is mostly uncertain, too many
things are happening too fast. If I had to I would bet on Java for server
technology and Flash for client technology. The performance of Java6 have
left PHP and the many other scripting languages panting for air way way
behind. And its scripting API has engulfed all the good things about
scripting languages into its domain. And yet the most important thing about
Java is its scalability. Let's be honest, how can anyone expect to beat Sun
in its own turf (networking)? Anyway, PHP developers, remember this word:
"Quercus".

And the Flash guys pulled a rabbit out of the hat and called it Flash 9.
They broke every compatibility known to developers, but finally developing
for Flash doesn't suck. And also, they are going with the open-source
approach as the Sun guys did (I pity the poor graphic designer, he still has
to get a commercial license to author some content for the flash
environment). And we have now many tools to apply the AJAX technique and
DHTML easily, but I would still beat the crap out of anyone who thinks that
building a thick client on HTML DOM and javascript is a good idea.

On the other hand, there hasn't happened anything important on the PHP
frontier, except for the PHP4 EOL and the Zend Framework (IMHO the first
real framework for PHP). And the most annoying thing is this stupid marriage
PHP/MySQL that keeps on going. The moment was appropriate for PHP to end
this relationship and PDO was a good step towards this. You'll probably have
heard or will soon hear about mysqlnd, and many will think "yay! mysql
functions are again part of the core!!! and they're faster!!!" and I would
be thinking "damn! open source php projects will be tightly tied to MySQL,
AGAIN!".

Anyway that was much of a rant. The short version is "I liked the php
development market because it was safe, but now I doubt its safety".

That's all. I don't think that rant may be of use to anyone, but at least it
felt nice to let go of some steam.

Best Regards and Happy New Year,

Martin Alterisio


[PHP] Sayonara PHP

2007-12-25 Thread Martin Alterisio
Please let me do a little explanation of the title first. Japanese is an
interesting language where context is vital to the meaning of a word.
Sayonara usually means a simple "good bye", but within a different context
can mean "we'll probably never meet again".

To understand this mail you'll have to know that I was just another user of
PHP, an user that was probably too eager. I wanted to get more involved with
the development of PHP as I do believe in all the philosophy of open-source.
In the end I found my attempts ended in frustration, but, nevertheless, I
learned a lot in just a few months. I don't want this mail to be one where I
get to display all my frustration, instead I want to leave here all my
findings, the things I researched, the few things I managed to actually
code, and mostly the ideas that someone else might find useful.

 To those who may want to involve in the php internals 

For those in the generals list that may ever try to venture in the internals
of PHP, remember that you have to back your point of view with a patch. So,
sit down, remember the old days in college using the c compiler, and code
like a cowboy before trying to promote anything in the internals. It's the
status quo of the PHP development community, as I did learn too late.

 Namespaces: function imports 

Here is the patch to add function imports to 5.3. To be consistent constants
imports have to be added too:

http://martinalterisio.com.ar/php5.3/use.function.v2b.patch

If you don't know what imports are, they are just a way to refer to a longer
name with a shorter name. For example:

http://martinalterisio.com.ar/php5.3/file.scope.use.patch

With this the use statement is checked only against the names used in the
current file (or namespace if using multiple namespaces per file). Since the
imports only affect the current file, this is more sensible, and the issue
mentioned before disappears.

 Name clash and ambiguity issue introduced by namespaces 

There's another pending issue with namespaces, there's a name clash that
currently goes undetected, and makes static methods partially unavailable.
This is due to the fact that using :: as namespace separator generates
ambiguity. foo::bar() can refer to the static method bar in class foo, or to
the function bar in the namespace foo. This is an issue to php library
developers. Someone can inject a namespaced function which overrides your
static method.

One possible solution I approached was to prevent the name clash altogether,
but I found this approach inappropriate for 2 reasons: the performance
impact is too big; is not consistent with how other name clashes are handled
in php (classes and functions may have the same name).

Another approach, which I believe is the correct one but never got the
chance to implement in a patch, is to change the order of name resolution,
search first the static method and then the namespaced function, and if the
user wants to refer to the function he can import the function. This way
both remain accessible although the user has to solve the ambiguity. Also
this reduces the impact of adding namespaces on legacy code, since there's
an impact to all static method calls (because first the namespaced function
is searched).

 Reducing impact on performance introduced by namespaces 

I found out that although the philosophy behind the namespaces
implementation is to do as much as possible in compile time, but much is
pushed to the executor. Those could be solved on compile time. Much can be
optimized changing the name resolution rules. If these become more explicit,
the compiler can discern which is the actual name that's referred to. As of
now, it can be optimized using imports and explicit names, which are used as
alternative notation. In other words, the normal use of namespaces is not
optimal.

There's still one name resolution that seems inevitable that it will fall to
the executor: the ambiguity mentioned earlier between static methods and
namespaced functions. This could be solved by the user if the use statement
allows to also explicitly indicate the type of import: use class X; use
namespace X; use function X; use const X;

 Fix name resolution rules for better coding practices 

Also, as of now, I'm more than confident when I say that the current name
resolution rules will bring much headaches to users. For starters you'll
have to make a habit of prefixing :: to all internal function calls (such as
::count, ::strlen, etc). This way will be safer for creating php libraries,
since another user could inject a namespaced function that overrides those
functions. This is because the function call without that prefix will try
first a function in the same namespace then the internal. Also, for this
same reason, using the :: prefix will be faster (since it's solved at
compile time). And if you want to refer to an element of the current
namespace, is better to use namespace::

If you don't know about the 

Re: [PHP] Try{} Catch()

2007-12-23 Thread Martin Alterisio
It's not supposed to be practical, it's just a way to handle errors. You
shouldn't rely on try/catch for algorithm implementation.

You create exceptions for errors and unexpected behavior. Then in some other
part of the system you use try/catch to prevent the code from terminating
abruptly. You catch the exception (you should know which exceptions can be
thrown), and act accordingly. Either closing resources, add a log message
with debug information, and/or sending an error message to the user.

2007/12/23, Al <[EMAIL PROTECTED]>:
>
> Try() and Catch() seems neat; but, I've not found it to be very practical.
>
> Anyone using it? How?
>
> Al...
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


Re: [PHP] // ?>

2007-12-04 Thread Martin Alterisio
2007/12/4, Kevin Schmeichel <[EMAIL PROTECTED]>:
>
> Here's some unexpected behavior:
>
>  // ?> what?
> ?>
>
> This will output "what?" - I expected no output, as is the case if the
> inline comment was a /* */ comment.  Is this a bug?
>

Expected behavior. Read the manual:

http://php.net/manual/en/language.basic-syntax.comments.php


Re: [PHP] Structured Code vs. Performance

2007-12-03 Thread Martin Alterisio
2007/12/2, tedd <[EMAIL PROTECTED]>:
>
> Oh yes, it's very much like fractals, but the term "fractalism" is
> usually reserved for art forms based on fractals.
>
> However, one could conclude that all crystalline forms are a
> "real-world" examples of fractals. In similar vein, all repetitive
> processes (including programming) could be though of as a fractal
> dependant functions. Interesting food for thought, which also could
> be fractal dependant. :-)
>

Well, I don't know in your country, but here code is considered, legally
speaking, literature... that means we're actually doing ART

So fractalism is quite appropiate.

Even more, considering that fractal are a mathematical and algorithmical
constructs, it's more pertinent to talk about fractalism in terms of code
writing.


Re: [PHP] Structured Code vs. Performance

2007-12-02 Thread Martin Alterisio
2007/12/2, tedd <[EMAIL PROTECTED]>:
>
>
> To me, good structure starts at the function level. Like the lattice
> of a crystal, coding grows and reflects the most basic element. Keep
> that element consistent and you'll find that it will be reflected in
> everything you do.
>
> How's that for philosophical?
>

I even have a name for your philosophical doctrine: fractalism


Re: [PHP] sprintf() oddness

2007-12-02 Thread Martin Alterisio
2007/12/1, Christoph Boget <[EMAIL PROTECTED]>:
>
> Why does
>
> sprintf( '%.03f', 0.1525 )
>
> return 0.152 while
>
> sprintf( '%.03f', 0.1575 )
>
> return 0.158?
>


Welcome to the world of f floating point numbers. Discrete mathematics,
leave all hope, ye that enter.

It's the way floating point number behave (a computational error that's more
problematic that one may suspect). You'll have to live with it, or use an
extension for arbitrary sized numbers (or fixed point numbers).

Why we have to accept this kind of behavior?

Long story short: they are excellent for computations required in 3d
graphics, they are lousy for business applications...
...and we all know that computers are for playing 3d games, don't we?

XD

Sorry about the noise.


Re: [PHP] Code Critique Please :)

2007-11-26 Thread Martin Alterisio
2007/11/21, Simeon F. Willbanks <[EMAIL PROTECTED]>:
>
> Hello,
>
> I am trying to increase my knowledge and understanding of OO and OO
> Design Patterns.  I'd like to request a critique of a program that
> extracts MySQL table information and translates it into XML.  In the
> program, I tried to accomplish a few things:
>
> 1. Correct use of ADOdb
> 2. Closely match the PEAR coding standards
> - I encode my scripts in UTF-8
> - Not all indents are 4 spaces, but I have switched my IDE to
> treat
> tabs as four spaces
> - My phpDoc comments could probably use some tweaking
> 3. Object Oriented principles
> 4. Strategy Design Pattern
> - Interface used for column attribute parsing
>
> My overall goal is to use these xml files as a starting point to write
> a DAO with the Data Mapper Pattern.
>
> Here are the related files to peruse:
> http://simeons.net/code/datamapper/sql/photo_portfolio.sql
> - SQL dump
> http://simeons.net/code/datamapper/mysql_to_xml_oo.phps
> - Calling script
> http://simeons.net/code/datamapper/helpers/autoload.phps
> - Auto load classes
> http://simeons.net/code/datamapper/classes/DB.phps
> - ADOdb connection
> http://simeons.net/code/datamapper/classes/MySQLToXML.phps
> - MySQL extraction and parsing
> - XML writing
>
> Here are the outputted xml files:
> http://simeons.net/code/datamapper/xmldatamaps/album.xml
> http://simeons.net/code/datamapper/xmldatamaps/photo.xml
> http://simeons.net/code/datamapper/xmldatamaps/comment.xml
>
> Any comments are appreciated.
>
> Thanks,
> Simeon
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>
My 2 cents:

1) Do not use __autoload. Use SPL's spl_autoload_register().

2) Are you using one file per class? If not, you should.

3) Class names should be as self-explanatory as possible.
They should indicate what the class purpose is.

For example: MySQLToXML is too ambiguous as a class name. What does it do?
What aspect of MySQL translates to an XML?
MySQLToXML could be the name of the class package but not the name of the
class. I would have named it: MySQLDataToXMLExporter. Or preceding the name
with the package name: MySQLToXML_XMLExporter.

4) Class names shouldn't be verb conjugations. Use nouns instead.

e.g.: ParseDatabaseColumnAttribute is wrong, use something like
DatabaseColumnExporter or DatabaseColumnConverter or DatabaseColumnParser
(is not clear what its purpose is).

5) The use of __get with unrestricted access breaks encapsulation.

Your definition of __get in MySQLToXML provides access to any private var.
Did you actually intended that?
It doesn't look good anyway. Seems like a nasty workaround.

6) Function names should explain their purposes.

_setXmlDocuments doesn't set xml documents, it's actually building them.

Also, functions that start with get and set are usually expected to be just
getter and setters, which is usually associated with O(1) operations, or
O(logN)/O(N) in containers (meaning that it's not expected that a get or set
functions does more than just get or set a variable).

7) DON'T BE A SPORT COMMENTATOR!

Putting a comment on each line of code and just saying what it does actually
generates the opposite effect. It harms code readability and
maintainability. Also, it's a common sign of someone who was just forced to
put comments and didn't know how to do it.

You should use inline comments where relevant. If code is self-explanatory
(to a certain degree), inline comments are just a bother. You should use
inline comments whenever the action being done by the code cannot be grasped
just by looking at it, or whenever the code differs too much from usual
constructions that someone might not see what it's actually doing.

For example, compare the following:

// set table name
$tableName = $tableResultSet->fields[0];
// set xml document version and character encoding
$this->_xmlDocuments[$tableName] = ''
. "\n";
// open _xmlDocuments element for this table
$this->_xmlDocuments[$tableName] .= '<' . $tableName . '>' . "\n";
// fetch array with associative keys
$this->_dbConnection->setFetchMode(ADODB_FETCH_ASSOC);
// ADOdb result set of fields in the current table
$columnResultSet =
$this->_dbConnection->execute(sprintf($this->_dbConnection->metaColumnsSQL,
$tableName));
// loop until the end of the fields result set
while (!$columnResultSet->EOF) {

with this:

// loop initialization
$tableName = $tableResultSet->fields[0];
$this->_xmlDocuments[$tableName] = ''
. "\n";
$this->_xmlDocuments[$tableName] .= '<' . $tableName . '>' . "\n";
// we need associative arrays
$this->_dbConnection->setFetchMode(ADODB_FETCH_ASSOC);
$columnResultSet =
$this->_dbConnection->execute(sprintf($this->_dbConnection->metaColumnsSQL,
$tableName));
// loop through every record
while (!$columnResultSet->EOF) {


8) It seems that it's not the strategy pattern what you're using but the
builder pattern.

Re: [PHP] Regular Expressions

2007-11-06 Thread Martin Alterisio
2007/11/6, Alberto García Gómez <[EMAIL PROTECTED]>:
>
> I'm a mess in regular expressions and I make this code:
>
> $link = ereg_replace('ñ','n',$link);
> $link = ereg_replace('á','a',$link);
> $link = ereg_replace('é','e',$link);
> $link = ereg_replace('í','i',$link);
> $link = ereg_replace('ó','o',$link);
> $link = ereg_replace('ú','u',$link);
>
> I ask if is a way to make those lines into a single one but working as
> well as this piece. I'm thinking in increase those lines so will be
> wonderful if I can optimize the code.
>
>
>
> Este correo ha sido enviado desde el Politécnico de Informática "Carlos
> Marx" de Matanzas.
> "La gran batalla se librará en el campo de las ideas"
>

Use str_replace instead of ereg_replace. You don't need regular expressions
there.
Your code is good as it is, one line per string replacemente. Don't mess up
code readability just for the sake of some lousy optimization, it's not
worthy.



(in spanish)

Usa str_replace en lugar de ereg_replace. No necesitas expresiones regulares
en este caso.
Tu código está bien así, una línea por reemplazo. No arruines la legibilidad
del código solo por una optimización inútil, no vale la pena.


[PHP] A workaround for type hinting native types (and a little of self-advertising)

2007-11-06 Thread Martin Alterisio
$me->apologizeFor($this->isSelfAdvertising());
if ($you->lookingFor($php->workaround(TYPE_HINT_FOR_NATIVE_TYPES)) {
check('http://www.phpclasses.org/browse/package/4195.html');
}

$package = new Package('http://www.phpclasses.org/browse/package/4195.html'
);

$package->usageExample = <extensionExample = <<

Re: [PHP] counting with leading zeros

2007-10-01 Thread Martin Alterisio
// glob returns an ordered list (rtfm: man glob)
// relies on the use of the operator ++ to generate string sequences.

function lastFileInSequence($path, $prefix, $first, $suffix) {
return array_pop(glob($path . "/" . $prefix . str_repeat('?',
strlen($first)) . $suffix));
}

function nextFileInSequence($path, $prefix, $first, $suffix) {
if ($lastFile = basename(lastFileInSequence($path, $prefix, $first,
$suffix), $suffix)) {
return ++$lastFile . $suffix;
} else {
return $prefix . $first . $suffix;
}
}

$nextImage = $path . "/" . nextFileInSequence($path, "foo_", "01", ".jpg");

2007/9/26, brian <[EMAIL PROTECTED]>:
>
> I have a directory that contains many images (no, not pr0n,
> unfortunately) and i'm working on an admin script for adding to it. I've
> got something that works alright but i'm wondering if there's a Better
> Way.
>
> Each image is named like: foo_01.jpg, foo_02.jpg, bar_01.jpg, and so on.
> When adding a new image it should be assigned the next number in the
> series (the prefix is known). Thus, given the prefix 'bar' i do
> something like:
>
> function getNextImage($path, $prefix)
> {
>$pattern = "/^${prefix}_([0-9]{2})\.[a-z]{3}$/";
>
>$filenames = glob("${path}${prefix}*");
>
>if (is_array($filenames) && sizeof($filenames))
>{
>  sort($filenames);
>
>  /* eg. 'foo_32.jpg'
>   */
>  $last = basename(array_pop($filenames));
>
>  /* pull the number from the filename
>   */
>  $count = intval(preg_replace($pattern, '$1', $last));
>
>  /* increment, format with leading zero again if necessary,
>   * and return it
>   */
>  return sprintf('%02d', ++$count)
>}
>else
>{
>  return '01';
>}
> }
>
> Note that there almost certainly will never be more than 99 images to a
> series. In any case, i don't care about there being more than one
> leading zero. One is what i want.
>
> brian
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


Re: [PHP] Classes and access to outside variables

2007-09-30 Thread Martin Alterisio
That's incorrectly syntactically. Won't run.



Ok, let's write some code to show how this can be done:

class SearchHelper extends AjaxACApplication {
  private $dbh;
  public function __construct() {
$this->dbh = $GLOBALS['dbh'];
  }
}



Better yet, pass the database host in the construction:

class SearchHelper extends AjaxACApplication {
  private $dbh;
  public function __construct($dbh) {
$this->dbh = $dbh;
  }
}

$searchHelper = new SearchHelper($dbh);



Even better, DON'T use globals:

class DatabaseConnectionInfo {
  private var $host;
  ...
  public function getHost() {
return $this->host();
  }
  ...
  private static $defaultConnectionInfo;
  public static function getDefault() {
if (self::$defaultConnectionInfo === null) {
...build default connection...
}
return self::$defaultConnectionInfo;
  }
}

class SearchHelper extends AjaxACApplication {
  private $dbh;
  public function __construct(DatabaseConnectionInfo $connectionInfo = null)
{
if ($connectionInfo === null) {
  $connectionInfo = DatabaseConnectionInfo::getDefault();
}
$this->dbh = $connectionInfo->getHost();
  }
}

Yes, I know what you're thinking, too much more code for just a stupid
thing. Trust me, refactoring it's easier when the code was written right the
first time.

2007/9/30, 潘志彬 <[EMAIL PROTECTED]>:
>
> $dbh = 'test';
>
> class search_helper extends AjaxACApplication
> {
> /**
>  * Database connection details
>  */
>
>// announce global variable before use it
>global $dbh;
>
> $db_hostname = $dbh;
>
>
>...
>
> Regards,
> Ryu
>
>
>
> 2007/9/29, Merlin <[EMAIL PROTECTED]>:
> >
> > Hi there,
> >
> > I am new to PHP classes and I do want to access a variable outside the
> > class, but somehow that does not work. global also does not have any
> > effect.
> >
> > In the following example I would like to be able to access $dbh from
> > inside the class like I did in that example. This does not work. Can
> > somebody please give me a hint on the right syntax?
> >
> > $dbh = 'test';
> >
> > class search_helper extends AjaxACApplication
> > {
> > /**
> >  * Database connection details
> >  */
> >
> > var $db_hostname = $dbh;
> >
> > Thank you for any help,
> >
> > Merlin
> >
> > --
> > PHP General Mailing List (http://www.php.net/)
> > To unsubscribe, visit: http://www.php.net/unsub.php
> >
> >
>


Re: [PHP] Classes and access to outside variables

2007-09-29 Thread Martin Alterisio
Refer to the global on the constructor.

Anyway, using a global like that is not a good practice. Just pass the
variable to the constructor.

2007/9/29, Merlin <[EMAIL PROTECTED]>:
>
> Hi there,
>
> I am new to PHP classes and I do want to access a variable outside the
> class, but somehow that does not work. global also does not have any
> effect.
>
> In the following example I would like to be able to access $dbh from
> inside the class like I did in that example. This does not work. Can
> somebody please give me a hint on the right syntax?
>
> $dbh = 'test';
>
> class search_helper extends AjaxACApplication
>  {
>  /**
>   * Database connection details
>   */
>
>  var $db_hostname = $dbh;
>
> Thank you for any help,
>
> Merlin
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


Re: [PHP] function -> action

2007-08-10 Thread Martin Alterisio
2007/8/7, Richard Lynch <[EMAIL PROTECTED]>:
>
> On Fri, August 3, 2007 1:38 am, Ralph Kutschera wrote:
> >   I'm working on a project, where we distinguish between "functions"
> > and
> > "actions" in design, although in PHP both are implemented as
> > functions.
> > Is there a chance that PHP can use the word "action" as "function"?
> >
> > E.g.:
> > public function doSomething() {  }
> > public action doSomethingElse() { ... }
> >
> > ... is actually the same but would help to see the design also in the
> > code.
>
> You might be able to do this with the Run-Kit extension...


I was unaware that run-kit was able to do this kind of things, could you
explain a little more about how would this extension could handle code with
alien keywords.

It might be easier, however, to hack some kind of pre-processor that
> would search for PCRE '\\s*action\\s*' and replace it with ' function
> '
>
> You'd have to pre-process generate your actual PHP files that get
> executed, but the source you use would just have the 'action' in it.


Actually is not that simple. There are some considerations that should be
taken into account, such as the loss of error information (file and line
number where the error occurs) and exception information (stack trace does
not point to the right place), and parsing correctly the code as to replace
the action keyword where it actually applies. I made some experimentation
with preprocessing php code with added keywords, that might help you if you
wish to use such a solution:
http://www.phpclasses.org/browse/package/4001.html


Re: [PHP] function -> action

2007-08-10 Thread Martin Alterisio
2007/8/3, Ken Tozier <[EMAIL PROTECTED]>:
>
>
> On Aug 3, 2007, at 9:39 AM, Ken Tozier wrote:
>
> >
> > On Aug 3, 2007, at 2:38 AM, Ralph Kutschera wrote:
> >
> >> Hallo!
> >>
> >>   I'm working on a project, where we distinguish between
> >> "functions" and
> >> "actions" in design, although in PHP both are implemented as
> >> functions.
> >> Is there a chance that PHP can use the word "action" as "function"?
> >>
> >> E.g.:
> >> public function doSomething() {  }
> >> public action doSomethingElse() { ... }
> >>
> >> ... is actually the same but would help to see the design also in
> >> the code.
> >
> > You could define a generic action function
> >
> > function action($funcName, $funcArgs)
> > {
> >   return $funcName($funcArgs);
> > }
>
> Actually, this might be better as it makes no assumptions about the
> function's argument list.
>
> function action()
> {
> $func   = func_get_arg(0);
> $expr   = func_get_args();
> $expr   = array_slice($expr, 1);
> $expr   = implode(', ', $expr);
> $expr   = $func.'('.$expr.');';
>
> return eval($expr);
> }


Actually this function won't work as expected. The arguments are improperly
passed, they are not escaped and would only work with variables that hold
numeric values, one word strings that do no match to existing constants
(which will still trigger a notice in the error log). Also return values
will not be passed through, because a return statement was not included in
the eval'ed code.

eval is not the best solution for this:

function action() {
$func = func_get_arg(0);
$args = func_get_args();
$args = array_slice($args, 1);
return call_user_func_array($func, $args);
}


You lose the ability to pass by reference but that might not be
> important for your script.


That's not entirely true, objects are always references. You lose the
ability to pass any other type of value by reference.


Re: [PHP] Re: Design Dilemma - Database Data Abstraction

2007-04-11 Thread Martin Alterisio

2007/4/11, Roman Neuhauser <[EMAIL PROTECTED]>:


# [EMAIL PROTECTED] / 2007-04-09 19:45:41 -0300:
> Thanks but that's not what I'm looking for. As I said before, my problem
> isn't to find an implementation of an ORM, but that the concept I'm
working
> on will use a very restricted API (array operations), and I'm having
trouble
> to keep it coherent.

Yeah, it's a bad idea, and doesn't work.



If it is my idea that you think is bad and wouldn't work, I kindly ask if
you could explain your thoughs throughly. If it is not, I would also like to
know more about it, but if you fell it won't affect the thread of the
discussion.

Thanks.

Besides, what's with those funky ['s and ]'s? What are they for?

I didn't bother to RTFM.



The operator [] is known as the array access operator, is used to refer to
an item in an array through its index, which is contained inside the square
brackets. It is possible to overload this operator, and the basic related
actions (isset, unset, foreach), in PHP5.


Re: [PHP] Design Dilemma - Database Data Abstraction

2007-04-11 Thread Martin Alterisio

2007/4/10, Richard Lynch <[EMAIL PROTECTED]>:


On Sat, April 7, 2007 11:49 am, Martin Alterisio wrote:
> The solution I presented is to access, and act upon, a database as if
> they
> were PHP arrays, meaning that a table is presented as an array of
> records.

I don't quite get why you think this is any more fool-proof than using
a database in the first place, but okay, I guess...



It's not intended to be fool-proof, and I never said so. I said
"those-who-never-RTFM-proof", maybe some of those are fools, but many of
those have not received the proper preparation in computer sciences, and
maybe it's not their fault they can't read a manual meant for us coders to
read.

Anyway, if there is already an API that allows us to create objects that
look and act like PHP arrays, why don't just use that API for something like
an ORM?


My dilemma is as follows: a PHP array is a construct more restricted
> than a
> DB table. In a PHP array the index is either an int or a string, in a
> table
> de index can be any combination of fields. Then, my problem is how to
> design
> coherently the indexing of the arrays that represent the DB tables.



> I could index by the order as they are presented by the DB:

You have not specified any ORDER BY for the DB so far.



Why should I impose an order if the implementation may want to decide this
order.

By definition, then, the order is UNDEFINED and the DB is free to

return the result set in ANY order it finds convenient.



And that's okay, and I shall use the order the DB finds convenient.


$DB['users'][0] is the first user from the query "SELECT * FROM users"
> $DB['users'][1] is the second user from the query "SELECT * FROM
> users"
> etc..
>
> But this have many cons. First, without a deterministic order, the
> array can
> change its logic order on the whim of the DB, nobody assures that the
> order
> will be kept after a modification is made to the data, and this can be
> confusing and error prone:

Until you define an ORDER BY in the DB, there is no order, period.



If the DB presents the result sequentially there is an order, even if it
follows an undefined criteria.

If you *DO* define an ORDER BY in the DB, you'll have to be able to

write a PHP function which can duplicate that ORDER BY and
http://php.net/usort the array, or dis-allow changes to the array that
introduce new keys, and disallow using integer keys.



Why? I just let the DB manage the order. To use usort I'll have to actually
put the results in a real array, wasting memory, cpu time, and db access.


$name1 = $DB['users'][3]['name'];
> $name2 = $DB['users'][5]['name'];
> $DB['users'][3]['name'] = $name2;
> $DB['users'][5]['name'] = $name1;
>
> The last sentence may not be writing to the adequate record.

What's wrong here?



For example, if the current order for the 'users' table is by the 'name'
field, after the first write this order may have changed, then the record
we'll be trying to write next won't be the one we intended to.

If 5 isn't 5, then you are screwed from the get-go...


That's why I don't like this indexing criteria.


Another possible indexation could be by the value of the PK, but this
> also
> have some problems. First, it can be confusing if the PK is an
> autonumeric
> int, as this might be seen as a numeric indexation. Second, not all
> tables
> have only one field as PK (I can ask that all tables have at least a
> PK, but
> I can't ask that the PK is made of only one field).

Exposing an auto_increment field to anything above the DB layer is
almost always a Bad Idea (tm).



Why? Or, what do you mean by exposing the auto_increment field?

Show me one site that doesn't expose the value of this field (when needed)
in the url.


$user = $DB['users'][$userid]; // get
> $DB['users'][$userid] = $user; // update or insert
> $DB['users'][] = $userid; // insert
> unset($DB['users'][$userid]); // delete

I think you will find that detecting the array changes and pushing
them back down to the DB will be much more difficult than just
providing an API to a database in some kind of normalized functions...



That's the easy part, I'll just use the SPL interfaces. Sorry, I forgot to
mention this in my first email as I explained in the following emails.


There is also the problem with many-to-many relationships. If there
> was only
> one table that related two tables in this way, I could do the
> following:

Well, yeah...

You are going to have to have at least 2 if not 3 arrays to do that
with any efficiency at all...



Hey. Would you think I'll even propose this here if I didn

Re: [PHP] Re: Design Dilemma - Database Data Abstraction

2007-04-09 Thread Martin Alterisio

2007/4/9, Tony Marston <[EMAIL PROTECTED]>:



""Martin Alterisio"" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
>I have a dilemma on a design where I humbly ask your help. I'm working on
> the model part of a web application (not to be understood in the "web2.0
"
> way, but in a more general way, where anything mounted on HTTP is a web
> application) done in PHP5 following the MVC design pattern. But the
strong
> point is that the result must be those-who-never-RTFM-proof. But that's
> not
> my dilemma, I only mention this so that no RoR concept or similar is
> thrown
> into the table, that is, NO ActiveRecord.
>
> The solution I presented is to access, and act upon, a database as if
they
> were PHP arrays, meaning that a table is presented as an array of
records.
> Here comes my dilemma. But first let me explain a bit about the scenario
> so
> far:
>
> * It's aceptable that some restrictions are set upon the DB structure,
> only
> if at least the following constructions are allowed:
>  a) tables with only one field in the PK (usually an autonumeric int).
>  b) tables with a one-to-many relationship with itself, and one field PK
> (a
> tree structure).
>  c) tables with a one-to-one relationship, and at most two fields in the
> PK, and if there are two, one is a FK.
>  d) tables with a one-to-many relationship with one of the before
> mentioned
> tables, at most two fields in the PK, and if there are two, one is a FK.
>  e) tables that create a many-to-many relationship between two of the
> before mentioned tables, with possibly extra fields other than the
fields
> of
> the relationship, at most three fields int the PK, and if there are two
or
> more, two of them are FK.
>
> * The actions than will be more used to access the data will be:
>  a) get one record using its PK, or a combination of FKs where it
applies.
>  b) get one record using a unique key.
>  c) update or delete one record using its PK.
>  d) insert one record
>  e) loop on many records of one table, all or just one "page", or those
> related to a FK.
>  f) order the records before the loop
>
> My dilemma is as follows: a PHP array is a construct more restricted
than
> a
> DB table. In a PHP array the index is either an int or a string, in a
> table
> de index can be any combination of fields. Then, my problem is how to
> design
> coherently the indexing of the arrays that represent the DB tables.
>
> I could index by the order as they are presented by the DB:
>
> $DB['users'][0] is the first user from the query "SELECT * FROM users"
> $DB['users'][1] is the second user from the query "SELECT * FROM users"
> etc..
>
> But this have many cons. First, without a deterministic order, the array
> can
> change its logic order on the whim of the DB, nobody assures that the
> order
> will be kept after a modification is made to the data, and this can be
> confusing and error prone:
>
> $name1 = $DB['users'][3]['name'];
> $name2 = $DB['users'][5]['name'];
> $DB['users'][3]['name'] = $name2;
> $DB['users'][5]['name'] = $name1;
>
> The last sentence may not be writing to the adequate record.
>
> But this indexation has its pros. It can be used with a traditional for
> loop
> (although it will prove inefficient in most cases). And the records
after
> and before can be easily obtained.
>
> Another possible indexation could be by the value of the PK, but this
also
> have some problems. First, it can be confusing if the PK is an
autonumeric
> int, as this might be seen as a numeric indexation. Second, not all
tables
> have only one field as PK (I can ask that all tables have at least a PK,
> but
> I can't ask that the PK is made of only one field).
>
> But I have many pros with this strategy. I solve the actions on one
record
> using the PK (only if the PK is made of only one field):
>
> $user = $DB['users'][$userid]; // get
> $DB['users'][$userid] = $user; // update or insert
> $DB['users'][] = $userid; // insert
> unset($DB['users'][$userid]); // delete
>
> I think I could use other than ints and strings in the array index, but
I
> rather stick to keeping this as seemingly equal to PHP arrays. I also
> could
> use FK relationships to solve this, for example, if tone table has an
> index
> made of two fields, one is an FK to another table, I could make one
table
> look as an array inside the other:
>
> foreach ($DB['users'][$userid]['address_book'] as $address) {
> ...
> }
>
> In 

Re: [PHP] Design Dilemma - Database Data Abstraction

2007-04-09 Thread Martin Alterisio

2007/4/9, Lester Caine <[EMAIL PROTECTED]>:


Martin Alterisio wrote:
> I have a dilemma on a design where I humbly ask your help. I'm working
on
> the model part of a web application (not to be understood in the "web2.0
"
> way, but in a more general way, where anything mounted on HTTP is a web
> application) done in PHP5 following the MVC design pattern. But the
strong
> point is that the result must be those-who-never-RTFM-proof. But that's
not
> my dilemma, I only mention this so that no RoR concept or similar is
thrown
> into the table, that is, NO ActiveRecord.
>
> The solution I presented is to access, and act upon, a database as if
they
> were PHP arrays, meaning that a table is presented as an array of
records.
> Here comes my dilemma. But first let me explain a bit about the scenario
so
> far:

I snip there - too much detail without defining the problem ;)



Yeah, sorry about that, the concept seems a bit difficult to explain. I
didn't found anything similar to point as reference.

Database Data Abstraction normally refers to using a common internal

structure
which can be loaded from a range of database engines. It sounds as if you
have
no requirement to 'Abstract' the database, only to come up with a
persistent
object layer under a single database engine?



Nope. It's an abstraction layer where the API is the common array
operations, implemented through the SPL interfaces for that purpose. No
explicit database is involved, except that some constrains to the structure
of the data shall be involved.

You have indicated that you are looking for a multi-user system, and so the

raw data must be in the database, but as you have seen, the flexibility
afforded by any database engine is difficult to duplicate. The thing to
remember is that you should ONLY be reading the data you need for the
current
user, and so your persistent objects do not need to be as complex as you
seem
to be looking for. It is always faster to ask the database for an answer
than
to copy everything to PHP in order to work with it. With any decent
database
you can provide views of the data in a suitable format for the arrays you
need
display on the user interface.



I completely understand, that's why from the beginning I decided that no
precaching nor caching would be done, and lazy evaluation would be the way
to go. The array operations would be transparently mapped to their
counterpart db action when needed.

I tried to find something suitable to point you at, but it's difficult

http://www.appelsiini.net/~tuupola/php/DB_DataContainer/
Is probably in line with your current outline?



Thanks but that's exactly what I don't want to do.

--

Lester Caine - G8HFL
-
Contact - http://home.lsces.co.uk/lsces/wiki/?page=contact
L.S.Caine Electronic Services - http://home.lsces.co.uk
MEDW - http://home.lsces.co.uk/ModelEngineersDigitalWorkshop/
Treasurer - Firebird Foundation Inc. -
http://www.firebirdsql.org/index.php



Thanks for answering but my problem isn't how the abstraction will be
actually implemented, but that the API (the array interface) stays as
coherent as possible. If you have the time, please read what was snipped,
those are my thoughts about how to make the array API coherent and what
problems I encountered.

Thanks again.


Re: [PHP] Design Dilemma - Database Data Abstraction

2007-04-08 Thread Martin Alterisio

2007/4/8, Paul Novitski <[EMAIL PROTECTED]>:


At 4/7/2007 09:49 AM, Martin Alterisio wrote:
>The solution I presented is to access, and act upon, a database as if
they
>were PHP arrays, meaning that a table is presented as an array of
records.

This implies to me that you'll read a series of tables into arrays,
modify the arrays, then update or recreate the database tables from
the arrays.  I can't really see how this can work for multiple users
because as soon as a second user reads and starts modifying the data
there will be obvious discontinuities between the two data snapshots,
and updating the tables from one user will erradicate changes made by
others.  Is this a single-user application you're working on?



First of all, thanks for replying, I really appreaciate it.

Second, I'm sorry, in my wild search for help I made the mistake of making
assumptions that would only lead to problems of communication. I forgot to
mention the base idea for the implementation. Actually no real arrays are
made, just objects that look and function like normal arrays through the SPL
interfaces ArrayAccess, Countable, Iterator and IteratorAggregate.

Answering your question: no, this will be used in a multi-user enviroment.

Basically all "array" operations will be traslated to the corresponding DB
operation. No caching. No postponing operations. Except for the record
object, which I think I will implement it so that field updates are done on
object destruction, but I'm still thinking about this.


I could index by the order as they are presented by the DB:
>
>$DB['users'][0] is the first user from the query "SELECT * FROM users"
>$DB['users'][1] is the second user from the query "SELECT * FROM users"
>etc..
>
>But this have many cons. First, without a deterministic order, the array
can
>change its logic order on the whim of the DB, nobody assures that the
order
>will be kept after a modification is made to the data, and this can be
>confusing and error prone:
>
>$name1 = $DB['users'][3]['name'];
>$name2 = $DB['users'][5]['name'];
>$DB['users'][3]['name'] = $name2;
>$DB['users'][5]['name'] = $name1;
>
>The last sentence may not be writing to the adequate record.

Hmm.  I don't see why this wouldn't work -- you're not changing the
keys (3 & 5) required to point to those unique records.  I can see a
problem if $name1 and $name2 were themselves the keys, but you're not
doing that in this example.



Well, it could not work if those operations are translated on the spot to
the corresponding DB action.

If that were the problem, though, you could simply mandate a rule

that you can never change the key of an array element that represents
a data record, so that the record sequence remains what it was
originally.  However, making your program logic depend on the record
sequence as it was read from the database seems quite iffy anyway
[especially in a multi-user system]; I'd just use the data table's
primary key as the array key and leave it at that.  Random access rocks!


From what you write, it almost seems as though you're assuming that
these statements:

>$DB['users'][3]['name'] = $name2;
>$DB['users'][5]['name'] = $name1;

actually modify the database records they represent.  If so, what
system are you using?  I just don't see this happening using simple
PHP and MySQL.  When you read a data record into a PHP array [with,
for example, mysql_fetch_array()] that array is just a static copy of
the data and doesn't possess any dynamic updating power over the
database.  Or are you using an I/O class that you're not showing in
your example code that executes a modifying query each time an "array
element" is changed?



That's actually what will happen. Using the SPL is actually posible. Sorry,
mi mistake for not explaining it throughly.


Another possible indexation could be by the value of the PK, but this also
>have some problems. First, it can be confusing if the PK is an
autonumeric
>int, as this might be seen as a numeric indexation.

You can prefix an autonumber field with alphabetic characters to
force it away from numeric indexing:

 $sKey = str_pad($aDataRecord['recno'], $iPadLength,
'pk_00', STR_PAD_LEFT);
 $aArray[$sKey] = $aDataRecord;

 e.g., recno 12345 becomes array key 'pk_012345'

Using str_pad(...LEFT) ensures that the array keys will be in the
same sequence as the data records even though the autonumber values
will be composed of differing numbers of digits.   You just have to
choose a pad length that equals the longest series of digits your
database will generate for an autonumber field.



But sup

[PHP] Design Dilemma - Database Data Abstraction

2007-04-07 Thread Martin Alterisio

I have a dilemma on a design where I humbly ask your help. I'm working on
the model part of a web application (not to be understood in the "web2.0"
way, but in a more general way, where anything mounted on HTTP is a web
application) done in PHP5 following the MVC design pattern. But the strong
point is that the result must be those-who-never-RTFM-proof. But that's not
my dilemma, I only mention this so that no RoR concept or similar is thrown
into the table, that is, NO ActiveRecord.

The solution I presented is to access, and act upon, a database as if they
were PHP arrays, meaning that a table is presented as an array of records.
Here comes my dilemma. But first let me explain a bit about the scenario so
far:

* It's aceptable that some restrictions are set upon the DB structure, only
if at least the following constructions are allowed:
 a) tables with only one field in the PK (usually an autonumeric int).
 b) tables with a one-to-many relationship with itself, and one field PK (a
tree structure).
 c) tables with a one-to-one relationship, and at most two fields in the
PK, and if there are two, one is a FK.
 d) tables with a one-to-many relationship with one of the before mentioned
tables, at most two fields in the PK, and if there are two, one is a FK.
 e) tables that create a many-to-many relationship between two of the
before mentioned tables, with possibly extra fields other than the fields of
the relationship, at most three fields int the PK, and if there are two or
more, two of them are FK.

* The actions than will be more used to access the data will be:
 a) get one record using its PK, or a combination of FKs where it applies.
 b) get one record using a unique key.
 c) update or delete one record using its PK.
 d) insert one record
 e) loop on many records of one table, all or just one "page", or those
related to a FK.
 f) order the records before the loop

My dilemma is as follows: a PHP array is a construct more restricted than a
DB table. In a PHP array the index is either an int or a string, in a table
de index can be any combination of fields. Then, my problem is how to design
coherently the indexing of the arrays that represent the DB tables.

I could index by the order as they are presented by the DB:

$DB['users'][0] is the first user from the query "SELECT * FROM users"
$DB['users'][1] is the second user from the query "SELECT * FROM users"
etc..

But this have many cons. First, without a deterministic order, the array can
change its logic order on the whim of the DB, nobody assures that the order
will be kept after a modification is made to the data, and this can be
confusing and error prone:

$name1 = $DB['users'][3]['name'];
$name2 = $DB['users'][5]['name'];
$DB['users'][3]['name'] = $name2;
$DB['users'][5]['name'] = $name1;

The last sentence may not be writing to the adequate record.

But this indexation has its pros. It can be used with a traditional for loop
(although it will prove inefficient in most cases). And the records after
and before can be easily obtained.

Another possible indexation could be by the value of the PK, but this also
have some problems. First, it can be confusing if the PK is an autonumeric
int, as this might be seen as a numeric indexation. Second, not all tables
have only one field as PK (I can ask that all tables have at least a PK, but
I can't ask that the PK is made of only one field).

But I have many pros with this strategy. I solve the actions on one record
using the PK (only if the PK is made of only one field):

$user = $DB['users'][$userid]; // get
$DB['users'][$userid] = $user; // update or insert
$DB['users'][] = $userid; // insert
unset($DB['users'][$userid]); // delete

I think I could use other than ints and strings in the array index, but I
rather stick to keeping this as seemingly equal to PHP arrays. I also could
use FK relationships to solve this, for example, if tone table has an index
made of two fields, one is an FK to another table, I could make one table
look as an array inside the other:

foreach ($DB['users'][$userid]['address_book'] as $address) {
...
}

In this case address_book refers to another table rather than a field (I
would have to ask that there are no fields with the same name). This table
has an FK to the id of the users tables and one other record working as a
PK. Accesing the array this way I have one of the values of the PK (the user
id), and I use the other as the array index.

There is also the problem with many-to-many relationships. If there was only
one table that related two tables in this way, I could do the following:

$DB['users'][$userid]['groups'] <- groups where the user belongs
$DB['groups'][$groupid]['users'] <- the users of a group

There would be a third table other than users and groups which doesn't show
up. But, what to do when there is more than one relationship table for the
same two tables? And if the relationship table also had some extra fields?
Also the delete action presents some problems:

Re: [PHP] finding a particular record within a MySQL result set

2007-04-04 Thread Martin Alterisio

2007/4/4, James Tu <[EMAIL PROTECTED]>:


I've cross posted this to the MySQL list...

Here's my original post.

> Is there some quick way to do the following in MySQL?  (I know I
> can use PHP to search through the result set, but I wanted to see
> if there's a quick way using some sort of query)
>
> Let's say I know that Joe is from Maine.
> I want to do a query of all employees from Maine, ordered by hiring
> date, and figure out where Joe falls in that list. (i.e. which
> record number is he?)
>
> -James
>


Here's my new plan of attack...

Right now I'm trying to use PHP to do a binary search on the result
set so I don't have to traverse the entire result set.

I'm using PHP's mysql_data_seek() to move the pointer within the
result set and looking at the data to do the necessary comparisons.

What do people think of this approach?

-James

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



There is a previous thread in this list regarding the same topic:

http://marc.info/?t=11668863811

This is the solution I've used for this kind of problems, and posted as a
response to that thread:

http://marc.info/?m=116697534311544


Re: [PHP] References challenge with PHP4

2007-03-25 Thread Martin Alterisio

2007/3/23, Jochem Maas <[EMAIL PROTECTED]>:


Martin Alterisio wrote:
> 2007/3/20, Jochem Maas <[EMAIL PROTECTED] >:
>
> Robert Cummings wrote:
> > On Tue, 2007-03-20 at 11:52 +0100, Jochem Maas wrote:
> >> ok, I tried it in a whole number of variations -
> >> no joy.
> >>
> >> you should use php5 if you want this kind of reference
> >> stuff - in php5 it just works, php 4 will give you big headaches.
> >
> > Now now, don't be calling PHP5 "ALL THAT" when it can't do it
right
> > either (or did you not check it using PHP5 ;) ;)
>
> god knows what I did - obviously something different to what I
thought
> I was testing :-/
>
> > Everything works fine
> > in PHP4 (also for PHP5 in this case if you just understand that
static
> > vars are buggy *lol* -- and this is first time I've noticed this
> bug).
>
> I have never run into this bug before ... nice catch, seems like
> a viable item for a bug report.
>
>
> Actually, is not a bug, is expected behaviour and documented in the
manual
>
> http://php.net/static
>
> See the last section, named "references with global and static
variables"

I have 2 issues with this:

1. the docs specify php4/ZendEngine1 which suggests php5 is not prone to
this implementation error, the following code seems to suggest that from
the user's
POV the problem no longer exists (as long as there is no use of the
reference operator
inconjunction with objects) in php5 (using the erf operator in php5 with
objects is
almost always wrong anyway):

class Test {
public $foo;
private static $inst;
function get() { if(!isset(self::$inst)) self::$inst = new self; return
self::$inst; }
}
$foo = Test::get();
$foo2 = Test::get();

$foo->foo = "foo";
var_dump($foo, $foo2, ($foo === $foo2));

$foo2->foo = "bar";
var_dump($foo, $foo2);

2. should I have to care about the way something is implemented internally
in order to use a given piece of language functionality without running
into
problems that have a serious wtf factor? I feel not.

oh well.

>
> static and global are implemented internally as references, that makes
> storing references into static variables impossible (which can be solved
> by using arrays of references as seen in Robert Cummings example).



100% behind you. I suffered enough because of this when trying to make code
that works for both php4 and php5 (unsuccesfully most of the times), and
that's why I knew about this "expected behaviour". And if you ever tried to
work with recursion in both functions and abstract data types in older
versions of PHP you'll find the WTF factor being more annoying than ever
(most of the problems have been solved but I still have nigthmares about
$foo =& $foo->next; causing segmentation faults).


Re: [PHP] References challenge with PHP4

2007-03-21 Thread Martin Alterisio

2007/3/20, Jochem Maas <[EMAIL PROTECTED]>:


Robert Cummings wrote:
> On Tue, 2007-03-20 at 11:52 +0100, Jochem Maas wrote:
>> ok, I tried it in a whole number of variations -
>> no joy.
>>
>> you should use php5 if you want this kind of reference
>> stuff - in php5 it just works, php 4 will give you big headaches.
>
> Now now, don't be calling PHP5 "ALL THAT" when it can't do it right
> either (or did you not check it using PHP5 ;) ;)

god knows what I did - obviously something different to what I thought
I was testing :-/

> Everything works fine
> in PHP4 (also for PHP5 in this case if you just understand that static
> vars are buggy *lol* -- and this is first time I've noticed this bug).

I have never run into this bug before ... nice catch, seems like
a viable item for a bug report.



Actually, is not a bug, is expected behaviour and documented in the manual

http://php.net/static

See the last section, named "references with global and static variables"

static and global are implemented internally as references, that makes
storing references into static variables impossible (which can be solved by
using arrays of references as seen in Robert Cummings example).


Re: [PHP] Variable variables and references

2007-03-11 Thread Martin Alterisio

2007/3/10, Dave Goodchild <[EMAIL PROTECTED]>:


Hi guys, I have just read 'Programming PHP' (O'Reilly) and although I
think
it's a great book, I am confused about variable variables and references -
not the mechanics, just where you would use them.

The subject of variable variables is explained but no examples are given
as
to why and where you would utilise them.



There really aren't useful and you're well without knowing they even exist.
In my opinion they harm code readibility, so they shouldn't be used,
especially if what you're trying to do can be achieved in some other way.

There is a special case where I found them useful. If you play competitions
like the sort of codegolf, they can be used to reduce your code by a few
characters by doing some really nasty things.

As for references, the examples given with regard to passing and returning

by reference in functions is clear, but no real examples are given as to
when this would be a preferred approcah - in fact, the authors stress that
due to PHP's copy-on-write mechanism, it is not a frequently-used
approcah.



References are useful to simulate PHP5 objects behaviour in PHP4. They can
be useful in many ways but I've found myself having too many troubles when
overusing them, segfaults and the sort...

So my question - are there any 'classic' situations in which either should

be used, and where and when do you guys use them in your real-world
efforts?
--
http://www.web-buddha.co.uk



Re: [PHP] OT - Regular Expression

2007-02-09 Thread Martin Alterisio

PS: I think you can remove the last .*, leaving the assertion like this:
(?=.*8), and it will still work fine and probably faster (which dosen't
matter under these conditions). But I haven't tried that one (and have
already erased the test file I did to check the regular expression).

2007/2/9, Martin Alterisio <[EMAIL PROTECTED]>:


If you want to do it in one regular expression, without listing each case,
you can use a lookahead assertion:

/^(?=.*8.*)[0-9]{4}$/

The assertion (?=.*8.*) checks that the following matches the expression
contained (.*8.*) which fails if there is not an 8.

2007/2/9, Peter Lauri <[EMAIL PROTECTED]>:
>
> Best group member,
>
>
>
> I want to match a four digit number. I allow user to enter with *
> syntax. So
> 8* would match anything that starts with 8 and is 4 digit long so:
>
>
>
> /^8[0-9]{3}$/
>
>
>
> That was easy. Ok then my other case was: *8, so anything that ends with
> 8
>
>
>
> /^[0-9]{3}8$/
>
>
>
> Ok, now the tricky one comes: *8*, so match it incase 8 is anywhere in
> the
> number. Can be beginning, end or in the middle. The problem that I face
> I
> cannot find out a good way of doing this correctly. So I ended up with
> an
> expression like this:
>
>
>
> /^(8[0-9]{3}|[0-9]8[0-9]{2}|[0-9]{2}8[0-9]|[0-9]{3}8)$/
>
>
>
> This takes care of it and everything, BUT it is so ugly. What I actually
>
> need to construct is: A regular expression that checks if 8 is a part of
> the
> number, and then that it is four digit long.
>
>
>
> The pipe "|" is an OR operator, but are there not any "AND" operator in
> Regular Expressions? I have been trying to figure this out for a while
> now.
> Of course I am using the above syntax right now, but would like to strip
> it
> down. Maybe not for the performance, but for the beauty of it :-)
>
>
>
> If you have any comments and suggestions about this I would be happy.
>
>
>
> Best regards,
>
> Peter Lauri
>
>
>
> <http://www.dwsasia.com/> www.dwsasia.com - company web site
>
> <http://www.lauri.se/> www.lauri.se - personal web site
>
> < http://www.carbonfree.org.uk/> www.carbonfree.org.uk - become Carbon
> Free
>
>
>
>



Re: [PHP] OT - Regular Expression

2007-02-09 Thread Martin Alterisio

If you want to do it in one regular expression, without listing each case,
you can use a lookahead assertion:

/^(?=.*8.*)[0-9]{4}$/

The assertion (?=.*8.*) checks that the following matches the expression
contained (.*8.*) which fails if there is not an 8.

2007/2/9, Peter Lauri <[EMAIL PROTECTED]>:


Best group member,



I want to match a four digit number. I allow user to enter with * syntax.
So
8* would match anything that starts with 8 and is 4 digit long so:



/^8[0-9]{3}$/



That was easy. Ok then my other case was: *8, so anything that ends with 8



/^[0-9]{3}8$/



Ok, now the tricky one comes: *8*, so match it incase 8 is anywhere in the
number. Can be beginning, end or in the middle. The problem that I face I
cannot find out a good way of doing this correctly. So I ended up with an
expression like this:



/^(8[0-9]{3}|[0-9]8[0-9]{2}|[0-9]{2}8[0-9]|[0-9]{3}8)$/



This takes care of it and everything, BUT it is so ugly. What I actually
need to construct is: A regular expression that checks if 8 is a part of
the
number, and then that it is four digit long.



The pipe "|" is an OR operator, but are there not any "AND" operator in
Regular Expressions? I have been trying to figure this out for a while
now.
Of course I am using the above syntax right now, but would like to strip
it
down. Maybe not for the performance, but for the beauty of it :-)



If you have any comments and suggestions about this I would be happy.



Best regards,

Peter Lauri



 www.dwsasia.com - company web site

 www.lauri.se - personal web site

 www.carbonfree.org.uk - become Carbon Free






Re: Re[2]: [PHP] nested, referenced foreach & implicit current array pointer issues

2007-01-31 Thread Martin Alterisio

2007/1/30, speedy <[EMAIL PROTECTED]>:


Hello Martin,

> Tuesday, January 30, 2007, 8:45:50 PM, you wrote:
>
> function f()
> {
>global $arr;
>
>foreach($arr as $k=>$v) {
>$v->do_something();
>}
> }
>
>  I don't see your point anywhere... foreach iterates over a copy of
>  the array so where is the potential side-effect? Even so there will
>  be references if the items of the original array are references, or
>  if they are objects in PHP5, but that's expected behaviour. That's
>  the way many OOP languages have been implemented (eg: Java) without
>  coders having the problems you mention. Just give me one good
>  reason to even consider your proposal.


Humm, you seem to have misunderstood (& that could be one reason in
itself). In my example foreach() iterates over the original $arr array
(contrary to what you say) - and so may deeply nested fns in the called
do_something() method, making global + foreach construct
unuseable/"unstable" in non-trivial cases.



Damn, I hate localized documentation. The spanish manual isn't updated to
what foreach does in the latest PHP5, and I didn't bother to check the
english version. Foreach uses a copy only if the array is not a reference,
and that's why you have that problem. There is nothing wrong with the global
keyword, just use $GLOBAL['arr'] instead to avoid the reference, or create a
copy by assignment.

Anyway, I couldn't find this change of behaviour in the foreach in the
changelog, but it seems it have been introduced around may 2005. Maybe is
too late to complain, but, now that I know, I think this behaviour doesn't
seem right.


Re: [PHP] nested, referenced foreach & implicit current array pointer issues

2007-01-30 Thread Martin Alterisio

2007/1/30, speedy <[EMAIL PROTECTED]>:


Hello PHP crew,

As a followup to:

http://bugs.php.net/bug.php?id=22879



That's not a bug, just an user doing things the wrong way and blaming the
language.

I've stumbled upon this problem in a way:


function f()
{
   global $arr;

   foreach($arr as $k=>$v) {
   $v->do_something();
   }
}

After digging through the docs I found that $arr is in fact a reference to
original $arr, and (in a pretty complex/confusing doc. page about foreach)
came to a conclusion that the above construct is practically unusable with
the global keyword as do_something() can potentially affect $arr hidden &
implicit (*yuck*) current element pointer and thus quite _non-obviously_
side-effect parent foreach() (ie. side-effect hidden in the depths of its fn
calls).

It would be (perhaps) better if PHP would treat global as making globaly
defined $arr accessible from the local fn. namespace instead of assigning a
local name to be a reference?

Also if the price of implicit current element pointer is copying of
non-referenced array on foreach() to gain humanly-expected behaviour,
and its great potential of writing non-obvious/bad code, I must wonder if
there are any good use cases (except the trivial ones) where  current
pointer is actually fruitful?



I don't see your point anywhere... foreach iterates over a copy of the array
so where is the potential side-effect? Even so there will be references if
the items of the original array are references, or if they are objects in
PHP5, but that's expected behaviour. That's the way many OOP languages have
been implemented (eg: Java) without coders having the problems you mention.
Just give me one good reason to even consider your proposal.


Re: [PHP] preg_match problem

2007-01-23 Thread Martin Alterisio

2007/1/22, Beauford <[EMAIL PROTECTED]>:



... much blah blah blah ...

I've probably read 100 pages on this, and no matter what I try it doesn't
work. Including all of what you suggested above - is my PHP possessed?

if(preg_match("/[EMAIL PROTECTED]&()*;:_.'/\\ ]+$/", $string)) { gives me
this error.

Warning: preg_match() [function.preg-match]: Unknown modifier '\' in
/constants.php on line 107

So if If you wouldn't mind, could you show me exactly what I need right
from
the beginning and explain why it works.

i.e.

if(preg_match(what goes here", $string)) {
Echo "You got it";



if (preg_match('/[EMAIL PROTECTED]&()*;:_.'\\/ ]+$/', $string))

Use single quotes and double back-slashes. PHP strings also have escape
sequences that use the back-slash as escape character, that's why you have
to double them. And single quotes to avoid the $ character interpreted as
the start of a variable.

PS: Will we be risking going the perl way if we ask that PHP supported
regular expressions natively (I mean: without having to provide them as
strings)?


Re: [PHP] preg_match problem

2007-01-21 Thread Martin Alterisio

2007/1/20, Arpad Ray <[EMAIL PROTECTED]>:


Martin Alterisio wrote:
> Double slash to prevent PHP interpreting the slashes. Also using single
> quotes would be a good idea:
>
> if (preg_match('/[\\w\\x2F]{6,}/',$a))
>

Just switching to single quotes would do the trick - you don't need to
escape anything but single quotes, and backslashes if they are the last
character.

Arpad



It's true, it works but I still believe is best to do both, since you may
forget to doubleslash when it's imperative for the expression to work, even
when using single quotes.


Re: [PHP] preg_match problem

2007-01-20 Thread Martin Alterisio

Double slash to prevent PHP interpreting the slashes. Also using single
quotes would be a good idea:

if (preg_match('/[\\w\\x2F]{6,}/',$a))


2007/1/19, Németh Zoltán <[EMAIL PROTECTED]>:


Hi all,

I have a simple checking like

if (preg_match("/[\w\x2F]{6,}/",$a))

as I would like to allow all "word characters" as mentioned at
http://hu2.php.net/manual/hu/reference.pcre.pattern.syntax.php
plus the '/' character, and at least 6 characters.

But it throws

Warning: preg_match(): Unknown modifier ']'

and returns false for "abc/de/ggg" which string should be okay.
If I omit the "\x2F", everything works fine but "/" characters are not
allowed. Anyone knows what I'm doing wrong? Maybe "/" characters can not
be put in patterns like this?

Thanks in advance,
Zoltán Németh

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




Re: [PHP] nuSoap -method '' not defined in service

2007-01-20 Thread Martin Alterisio

Try the following:

$server->register('getColumns', array(), array());

The second argument is an array containing an entry for each argument of the
webservice call, and the third argument is an array for the return value.
Since you don't have either arguments nor return value, empty arrays should
be provided.

Also I think you should call $server->configureWSDL(), before
registering anything.

2007/1/18, blackwater dev <[EMAIL PROTECTED]>:


I have the following code but when I hit the page, I get the xml error of
method '' not defined in service.  I don't have a wsdl or anything
defined.
Is there more I need to do to get the SOAP service set up?

Thanks!

include("nusoap/nusoap.php");

$server=new soap_server();
$server->register('getColumns');

function getColumns(){

$search= new carSearch();

return $search->getSearchColumns();

}
$server->service($HTTP_RAW_POST_DATA);




Re: [PHP] classes and objects: php5. The Basics

2007-01-16 Thread Martin Alterisio

Forgot to mention that calling a non-statical function this way should
generate an E_STRICT warning.

2007/1/16, Martin Alterisio <[EMAIL PROTECTED]>:


Backward compatibility with PHP4, where member functions couldn't be
declared as static. Any member function could be called statically providing
a static context instead of an object instance.

2007/1/16, Cheseldine, D. L. <[EMAIL PROTECTED]>:
>
> Hi
>
> I'm stuck on The Basics page of the php5 Object Model:
>
> http://uk.php.net/manual/en/language.oop5.basic.php
>
> The top example has the code:
>
> A::foo();
>
> even though foo is not declared static in its class.  How does it get
> called statically without being declared static?
>
> regards
> dave
>
> --
> PHP General Mailing List ( http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>



Re: [PHP] classes and objects: php5. The Basics

2007-01-16 Thread Martin Alterisio

Backward compatibility with PHP4, where member functions couldn't be
declared as static. Any member function could be called statically providing
a static context instead of an object instance.

2007/1/16, Cheseldine, D. L. <[EMAIL PROTECTED]>:


Hi

I'm stuck on The Basics page of the php5 Object Model:

http://uk.php.net/manual/en/language.oop5.basic.php

The top example has the code:

A::foo();

even though foo is not declared static in its class.  How does it get
called statically without being declared static?

regards
dave

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




Re: [PHP] Basic question - Starting a background task without waiting for its end.

2007-01-01 Thread Martin Alterisio

2006/12/31, Michel <[EMAIL PROTECTED]>:



I (very simply) try to open a "notepad" on a simple text file in a
simplistic PHP script, and would like to go on and display the next page
without waiting for this notepad to be shut.

After various attempts, I have used an :

exec ('bash -c cmd /C start /MAX notepad "my_file" > NUL');

... but it still wait for the shutting of the notepad ..!

Could anybody help me ?

For clarification :
1) I use this script on a machine which is in the same time "server" and
"client", which gives "meaning" to this operation.
2) I use "bash -c" because I have the cygwin platform which can easily
initiate tasks in background, but it could be suppressed, because it "de
facto" changes nothing...

Thank's for help.

Michel.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Have you tried the following?

exec ('bash -c cmd /C start /MAX notepad "my_file" > NUL &');


Re: [PHP] array_intersect problem

2006-12-25 Thread Martin Alterisio

2006/12/25, Leo Liu <[EMAIL PROTECTED]>:


Hi,

  I try to intersect associative array and it seems to fail to do so. Can
anyone show me a walk around?

  For example I have

  array1

  Array
(
[0] => Array
(
[imageID] => 1
)

[1] => Array
(
[imageID] => 2
)

[2] => Array
(
[imageID] => 3
)

[3] => Array
(
[imageID] => 4
)
)

  And array 2

  Array
(
[0] => Array
(
[imageID] => 6
)

[1] => Array
(
[imageID] => 3
)
)

  After intersection instead of me getting 3 as a result, I got the array
1 unchanged. Seems like intersection doesn't take place at all. Anyway to
solve this problem?

  Regards,

  Leo




Reality starts with Dream



Quote from php manual, in the reference for the array_intersect function:

*Note: * Two elements are considered equal if and only if (string) $elem1
=== (string) $elem2. In words: when the string representation is the same.

That's why array_intersect isn't working with your arrays.

If you're using PHP5 you could use array_uintersect, and compare the items
by the imageID:

   function compareByImageID($elem1, $elem2) {
   return $elem1['imageID'] - $elem2['imageID'];
   }

   $intersection = array_uinsersect($array1, $array2, 'compareByImageID');

Or you can do the following, which works in PHP4, but is not as versatile as
array_uintersect:

   class InArrayFilter {
   var $arr;

   function InArrayFilter($arr) {
   $this->arr = $arr;
   }

   function filterFunction($elem) {
   return in_array($elem, $this->arr);
   }
   }

   $filter = new InArrayFilter($array2);
   $intersection = array_filter($array1, array($filter, 'filterFunction'));


Re: [PHP] Clarification: Jump to a record/PHP paging...

2006-12-25 Thread Martin Alterisio

2006/12/25, Robert Cummings <[EMAIL PROTECTED]>:



WRONG! See Martin Alterisio's post for the same thread. You must not
have understood the OP's requirements.



xD
I was starting to think my mails weren't getting through the list, maybe its
nothing else than only a bigger delay than the usual. Anyway, I kind of lost
the topic of your discussion there... if you're so kind to explain in such a
way that an idiot like me can understand...

And Merry Xmas, Merry hangover or anything else you should desire to
celebrate.

PS: was my previous post useful to anyone? or did I mess up the explanation?
I'm not sure... =S that's why I'm asking...


Re: [PHP] Odd behavior

2006-12-25 Thread Martin Alterisio

2006/12/25, jekillen <[EMAIL PROTECTED]>:



On Dec 25, 2006, at 7:21 AM, Roman Neuhauser wrote:

> # [EMAIL PROTECTED] / 2006-12-24 18:11:03 -0800:
>> function display($list, $in, $out, $save, $req, $x)
>>  {
>>   for($i = 0; $i < count($in); $i++)
>>   {$j = $i + 1;
>>   // two sets of links displayed instead of one
>>  for($i = 0; $i < count($out); $i++)
>>   {$j = $i + 1;
>> // two sets of links displayed instead of one
>>   for($i = 0; $i < count($save); $i++)
>>{$j = $i + 1;
>>  // two sets of links displayed instead of one
>>   for($i = 0; $i < count($req); $i++)
>>{$j = $i + 1;
>>  // two sets of links displayed instead of one
>
>> The print lines above are supposed to produce a list of links to
>> files.
>> In the web display I get duplicate sets of links which seems to mean
>> that the loops in the function are running twice, and in one instance
>> three times instead of once.
>
> Look at the variable names you use for iteration.
>
Thanks, Usually, when a variable name like $i is used and then
reset to 0 in the next loop it does not matter. But I solved the
problem and posted the solution.  I also solved the regex
problem. There was an extra \n sneaking into the test pattern
so I could not get a match. I am not sure where the extra \n is
coming from.
It looks like I didn't post the solution after all:
Update:
I solved the double loops problem with this code change:

function display($list, $a, $x)
 {
  for($i = 0; $i < count($a); $i++)
 {$j = $i + 1;
  print "$j\n";
 };
  }
and:

if($list || $current)
   {
 switch($list)
   {
case 'in':
display($list, $in, $x);
break;
case 'out':
display($list, $out, $x);
break;
case 'save':
display($list, $save, $x);
break;
case 'req':
display($list, $req, $x);
break;
   }
   }
Apparently what was happening was that the code running under 5.1.2
was trying to process all the arrays that had values in spite of the
switch
statement in the original display() function. If the was an $in array
the
switch  would process that for the $list value being 'in' but since
there
was also a save value, the switch tried to process it also, even though
'save' wasn't the $list value. I found it would do this for all arrays
that
had values. So if three had values the loop selected loop would run
three times.
Could this be a bonafide bug?
JK



I suspect this is an EBSAC bug, but I'm not completely sure. Anyway, please
consider improving your coding style, its all messy and unreadable. Also,
you should provide a description of the calling conditions, since there
might be the cause of the error in the function.


Re: [PHP] Clarification: Jump to a record/PHP paging...

2006-12-24 Thread Martin Alterisio

To solve a problem like yours I ussualy do the following:

First you need to use a deterministic order criteria when displaying the
results, this means that according to the order columns you provide, MySQL
will not have to decide how to order two rows that have the same values for
this columns. For example, if you order an users table by the first name of
the user, there might be two users with the same name, and MySQL will order
them the way it founds more convenient.

One way to do this is using an uniquely indexed column in the order
criteria. The primary key would be a nice idea. You don't need to enforce an
order criteria to the listing, you can simply add the primary key as the
last column in the order by and that will be enough.

Then, look for the record you need and store the values it has for the
columns used in the order. With that info you can build a query which will
return how many records there are, in the listing, before the one you sought
before:

SELECT COUNT(*)
 FROM table
WHERE order_column1 < 'order_column1_value'
OR (order_column1 = 'order_column1_value' AND order_column2 <
'order_column2_value')
OR (order_column1 = 'order_column1_value' AND order_column2 =
'order_column2_value' AND order_column3 < 'order_column3_value')
...etc...

If the order direction of one column is descending instead of ascending, you
should use > instead of < for that specific column.

If you're worried about performance you should add indexes to the columns of
the order criteria, which you probably have done so anyway. Also you should
consider splitting this query in many queries:

SELECT COUNT(*)
 FROM table
WHERE order_column1 < 'order_column1_value'

SELECT COUNT(*)
 FROM table
WHERE order_column1 = 'order_column1_value'
   AND order_column2 < 'order_column2_value'

SELECT COUNT(*)
 FROM table
WHERE order_column1 = 'order_column1_value'
   AND order_column2 = 'order_column2_value'
   AND order_column3 < 'order_column3_value'

etc...

and sum all the results. It seems that sometimes this run faster with a
MySQL server, anyway, give it a try if you're worried about the query
performance.

The result will be the number of records before the one you sought, with
that info getting the page of the record is piece of cake.


2006/12/23, T.J. Mahaffey <[EMAIL PROTECTED]>:


I see now that I did not explain myself adequately.
I think "jump to record" was the wrong way to put it. So, here goes.

I already have excellent paging functionality working well, based on
a nice tutorial at PHPFreaks.

My problem is that when a user performs a search, I need to display
the page on which their search string is found, but still display ALL
records within the paging of the entire database.
I've since discovered the core of what I need to do:

1. I can find the record I need through a simple query.

2. I can easily determine WHICH page this record is on by counting
BACKWARDS from the found record to the FIRST record, totaling the
number of records from record 1 to the found record. Then, by
performing a bit of division, I can determine which page that record
appears on and direct the user to "...page=8" via $_GET.

SO, my question is: how might I have MySQL tell me how many records
came BEFORE the found record?
(FYI: there is currently no auto-incrementing ID on these records, so
that obviously easy solution would be unavailable.)

Thanks in advance for any insight.

--
T.J. Mahaffey
[EMAIL PROTECTED]

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




Re: [PHP] EZ array problem - What's wrong with my brain?

2006-12-04 Thread Martin Alterisio

2006/11/30, Brian Dunning <[EMAIL PROTECTED]>:


var_dump() gives me this:

array(1) {
   ["1.2"]=>
   array(2) {
 ["code"]=>
 array(1) {
   [0]=>
   string(3) "111"
 }
 ["status"]=>
 array(1) {
   [0]=>
   string(3) "new"
 }
   }
}

I'm trying to set a variable to that "1.2". Shouldn't I be able to
get it with $var = $arr[0][0]?

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



$keys = array_keys($var);
var_dump($keys[0]);

string(3) "1.2"

$values = array_values($var);
var_dump($values[0]);

array(2) {
  ["code"]=>
  array(1) {
[0]=>
string(3) "111"
  }
  ["status"]=>
  array(1) {
[0]=>
string(3) "new"
  }
}


Re: [PHP] Help on objects

2006-10-05 Thread Martin Alterisio

2006/10/5, Satyam <[EMAIL PROTECTED]>:




- Original Message -
*From:* Martin Alterisio <[EMAIL PROTECTED]>
*To:* Satyam <[EMAIL PROTECTED]>
*Cc:* Deckard <[EMAIL PROTECTED]> ; php-general@lists.php.net
*Sent:* Thursday, October 05, 2006 3:50 PM
*Subject:* Re: [PHP] Help on objects

2006/10/5, Satyam <[EMAIL PROTECTED]>:
>
> I've seen you already had a good answer on the errors in the code so I
> won't
> go on that.  As for OOP, the one design error you have is that you are
> asking for an action, not an object.   You want to make SQL inserts,
> that is
> your purpose, and that is an action, which is solved by a statement, not
> by
> an object.   There is no doer.  Objects are what even your English
> teacher
> would call objects while describing a sentence.  You are asking for a
> verb,
> you don't have a subject, you don't have an object.   Of course you can
> wrap
> an action in a class, but that is bad design.  Classes will usually have
> names representing nouns, methods will be verbs, properties adjectives,
> more
> or less, that's OOP for English teachers.
>
> Satyam
>

You're wrong, partially:


I am sure you could have stated that in a more courteous way.



I apologize, english is not my first language and I usually can't express
myself correctly. As a fellow compatriot I hope you'll understand there
weren't ill intentions on what I said.


Re: [PHP] Re: OOP Hello World

2006-10-05 Thread Martin Alterisio

2006/10/5, John Wells <[EMAIL PROTECTED]>:


On 10/5/06, Martin Alterisio <[EMAIL PROTECTED]> wrote:
> PHP seems to be getting more and more object oriented, I think it's the
> right time to start questioning what have been done so far in terms of
OOP
> in PHP, because, honestly, there are too many php classes being
distributed
> out there that are a complete mess. Forget about spaghethi code, we have
to
> deal with pizza classes too.

[code]
require_once('previousEmails.php');

interface Responder {
public function respond(Salutable $receiver, $response);
public function getResponderName();
}

class WiseAssResponder implements Responder {
protected $responderName;

public function __construct($responderName) {
$this->responderName = $responderName;
}

public function getResponderName() {
return $this->responderName;
}

public function respond(Salutable $receiver, $response) {
echo "Hi " . $receiver->getSalutationName()
   . ".  Please read my response
below: \n\n";
echo $response;
echo "Kindest Regards,\n" .
$this->getResponderName();
}
}

class Martin implements Salutable {
public function getSalutationName() {
return get_class($this);
}
}

$martin = new Martin();
$johnW = new WiseAssResponder('John W');
$response=<<


I'd rather say that we have different concepts of what is simple and
flexible, and both concepts are aceptable.

I know that plenty of people on this list want to have a serious

conversation about OOP for PHP (should we just start using OOPHP as
the new acronym?  or maybe POOPH?  Or... PHOOP?!? Wait, that's not
taking thing seriously...), but I don't think a complex Hello, World
made of Saluters, Salutables, factories and abstractions is taking it
serious.  I think it's exhausting the theory and using various design
patterns for the sake of using design patterns...



It seems we've differents approaches to what is complex and what is simple
(in terms of computer systems). I think being serious about OOP is start
thinking even the simplest of problem from an OOP perspective. I just
exposed the Hello World as an example, off course it seems like using a nuke
to kill a mosquito, but here I'm not thinking about efficiency or efficacy,
it's about training the mind into the OOP methodologies and ways of
thinking. Like training your body, once the mind sees everything in terms of
object abstraction, OOP will be as natural as breathing.

The kind of thinking that OOP it's just a *super* feature of a programming
language that should be used only for highly complex problems, is what I
want to eradicate. OOP doesn't stand neither as a language feature nor as
extra capabilities of a language, on the contrary, it takes some freedom
away from the programmer. I see OOP as a way of thinking and working, that
should be used in the most complex problem and the most simple problem
equally.

But really all of this comes down to the imutable truth about

programming in PHP: there are a *million* ways to skin a cat.  When
you heard "OOP + Hello, World", you thought about people/things
greeting each other.  When I heard it, I thought about an application
outputing a string.  The guy who started that particular thread
probably thought of something totally different.  Who's to say who is
right?



Off course, no one can say which is the right way to solve a problem, and I
will not hide the fact that OOP is just a coder's whim. I'm just inviting
you over to this whim, I can assure you that it's a healthy and beneficial
whim, it's not just a Java hype. At least it's healthier whim than web2.0.

Hey, take my words as mine alone though.  Maybe I was the only one

that got my joke.  It's happened before.



Nope, I caught your joke, and I found it amusing. Though every joke hides a
truth, as I can explain a hello world in oop laughing and being serious at
the same time.

HEREDOC;


$johnW->respond($martin, $response);
exit;
[/code]



Re: [PHP] Help on objects

2006-10-05 Thread Martin Alterisio

2006/10/5, Satyam <[EMAIL PROTECTED]>:


I've seen you already had a good answer on the errors in the code so I
won't
go on that.  As for OOP, the one design error you have is that you are
asking for an action, not an object.   You want to make SQL inserts, that
is
your purpose, and that is an action, which is solved by a statement, not
by
an object.   There is no doer.  Objects are what even your English teacher
would call objects while describing a sentence.  You are asking for a
verb,
you don't have a subject, you don't have an object.   Of course you can
wrap
an action in a class, but that is bad design.  Classes will usually have
names representing nouns, methods will be verbs, properties adjectives,
more
or less, that's OOP for English teachers.

Satyam



You're wrong, partially: an action can be an object and it's not necessarily
a bad design, take for example function objects or the program and
statements as objects in lisp-like languages. It's acceptable to make a
class that works as an abstract representation of an sql query. This kind of
classes are used very efficiently in object persistence libraries. What I
agree with you is that it's not right that this class works as the insert
action and not as a representation of the insert operation.


Re: [PHP] Help on objects

2006-10-05 Thread Martin Alterisio

2006/10/4, Deckard <[EMAIL PROTECTED]>:


Hi,

I'm trying to lay my hands on PHP OOP, but it's not easy :(
I've read several examples in the web, but cannot transpose to may case.

I'm trying to set a class to make SQL inserts in mysql.

I have the class:
-
table = $table;
  $this->sql   = $sql;

  return(TRUE);
}


  // function that constructs the sql and inserts it into the database
  function InsertDB($sql)
   {

print($sql);
// connect to MySQL
$conn->debug=1;
$conn = &ADONewConnection('mysql');
$conn->PConnect('localhost', 'deckard', 'ble', 'wordlife');

if ($conn->Execute($sql) === false)
print 'error inserting: '.$conn->ErrorMsg().'';

return (TRUE);
   }
}


and the code that calls it:

InsertDB('$sql');

?>


but it's not working ?

Can anyone give me a hand here ?

I've read the manuals, examples, etc.

Any help would be appreciated.

Best Regards,
Deckard

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



For database interaction, give PDO a chance: http://php.net/pdo
IMO it's cleaner and more efficient than adodb.

Then, I believe what you're trying to make is a query builder. I would break
down the differente parts of an sql query and create abstractions for each
part (some can be reused on different types of queries), then have builder
create the queries abstractions from the different parts.


Re: [PHP] Re: OOP Hello World

2006-10-05 Thread Martin Alterisio

Double-checking.

Nope.

It wasn´t from the Java mailing list, they're still talking about
hibernate... they'll probably give a damn about this thing anyway, because
they're all oop gurus, what would they care about a hello world?

PHP seems to be getting more and more object oriented, I think it's the
right time to start questioning what have been done so far in terms of OOP
in PHP, because, honestly, there are too many php classes being distributed
out there that are a complete mess. Forget about spaghethi code, we have to
deal with pizza classes too.

2006/10/5, John Wells <[EMAIL PROTECTED]>:


Are you sure you're not on a Spanish *Java* mailing list?

:)

On 10/5/06, Martin Alterisio <[EMAIL PROTECTED]> wrote:
> Me... again, still boring you to death with meaningless OOP rantings.
>
> First I would like to point out that there was a design mistake in what
I
> proposed in the last mail (following afterwards): the Saluter shouldn't
be
> an abstract class, it isn't correct to base your class hierarchy on the
> ability to greet (or in the ability to do something generally speaking).
If
> it's done that way we'll have classes coexisting in the same branch of
the
> class tree, but possibly having completely different nature. Saluter
should
> be an interface:
>
>   interface class Saluter {
> public function greet(Salutable $receiver);
>   }
>
>   class FormalSaluter implements Saluter {
> public function greet(Salutable $receiver) {
>   echo "Hello " . $receiver->getSalutationName() . "\n";
> }
>   }
>
> Then, I'll try to translate what has been said in the spanish list.
>
> It has been proposed that World should be a singleton, since there is
only
> one world... but this arguable, at metaphysic level perhaps...
>
> Also an observer pattern could be used so anyone can hear the greetings.
But
> I think this should be done on the design of the greeting enviroment
> abstraction (to provide other places than standard output where the
greeting
> can be said).
>
> The saluters factory should use a factory method pattern or an abstract
> factory pattern? I think an abstract factory is not appropiate in this
case,
> the creation process is not that complex to require this kind of design
> pattern.
>
> Also I proposed that decorators could be used to add styles to the
greeting
> for outputs that allow styling (e.g.:html). In this case maybe an
abstract
> factory would be appropiate, so that decorated saluters are created for
the
> appropiate type of output, combined with a builder pattern to create the
> decorated saluters (this last part I thought it just now, I'll post it
later
> on the spanish list)
>
> Well, I think that sums it all up.
>
> 2006/9/29, Martin Alterisio <[EMAIL PROTECTED]>:
> >
> > What's up folks?
> >
> > I just wanted to tell you about a thread that's going on in the
spanish
> > php mailing list. A fellow software developer which had just started
with
> > OOP was asking for "Hello World" examples using OOP. The examples of
code he
> > had been doing was not that different from the usual Hello World
example we
> > all know and love(?), so I thought he was missing the point of what
was the
> > purpose of using OOP. This was my reply (I'll try to keep the
translation as
> > accurate as possible):
> >
> > I believe you have misunderstood what is the purpose of OOP, your
objects
> > are not proper abstractions.
> >
> > First and most important, you should define what is the problem to
solve:
> > greet the world.
> > We build an abstraction of the problem and its main components:
somebody
> > who greets and something to greet.
> > Here we're working with generalizations, since our main objective is
to
> > build reusable objects. For that purpose is useful that our "saluter"
could
> > be used to greet more than just the world.
> >
> > Therefore we'll first define what kind of interaction we expect the
> > salutation receivers to have, in the following interface:
> >
> >   interface Salutable {
> > public function getSalutationName();
> >   }
> >
> > In this interface we have all we need to properly greet any entity:
the
> > name we should use when doing the salutation.
> >
> > Then we create the object which represents the world:
> >
> >   class World implements Salutable {
> > public function getSalutationName() {
> >   return "World";
> > }
> >   }
> >
> > Now we're missing a saluter, but we're not sure which way of greeting
&g

[PHP] Re: OOP Hello World

2006-10-04 Thread Martin Alterisio

Me... again, still boring you to death with meaningless OOP rantings.

First I would like to point out that there was a design mistake in what I
proposed in the last mail (following afterwards): the Saluter shouldn't be
an abstract class, it isn't correct to base your class hierarchy on the
ability to greet (or in the ability to do something generally speaking). If
it's done that way we'll have classes coexisting in the same branch of the
class tree, but possibly having completely different nature. Saluter should
be an interface:

 interface class Saluter {
   public function greet(Salutable $receiver);
 }

 class FormalSaluter implements Saluter {
   public function greet(Salutable $receiver) {
 echo "Hello " . $receiver->getSalutationName() . "\n";
   }
 }

Then, I'll try to translate what has been said in the spanish list.

It has been proposed that World should be a singleton, since there is only
one world... but this arguable, at metaphysic level perhaps...

Also an observer pattern could be used so anyone can hear the greetings. But
I think this should be done on the design of the greeting enviroment
abstraction (to provide other places than standard output where the greeting
can be said).

The saluters factory should use a factory method pattern or an abstract
factory pattern? I think an abstract factory is not appropiate in this case,
the creation process is not that complex to require this kind of design
pattern.

Also I proposed that decorators could be used to add styles to the greeting
for outputs that allow styling (e.g.:html). In this case maybe an abstract
factory would be appropiate, so that decorated saluters are created for the
appropiate type of output, combined with a builder pattern to create the
decorated saluters (this last part I thought it just now, I'll post it later
on the spanish list)

Well, I think that sums it all up.

2006/9/29, Martin Alterisio <[EMAIL PROTECTED]>:


What's up folks?

I just wanted to tell you about a thread that's going on in the spanish
php mailing list. A fellow software developer which had just started with
OOP was asking for "Hello World" examples using OOP. The examples of code he
had been doing was not that different from the usual Hello World example we
all know and love(?), so I thought he was missing the point of what was the
purpose of using OOP. This was my reply (I'll try to keep the translation as
accurate as possible):

I believe you have misunderstood what is the purpose of OOP, your objects
are not proper abstractions.

First and most important, you should define what is the problem to solve:
greet the world.
We build an abstraction of the problem and its main components: somebody
who greets and something to greet.
Here we're working with generalizations, since our main objective is to
build reusable objects. For that purpose is useful that our "saluter" could
be used to greet more than just the world.

Therefore we'll first define what kind of interaction we expect the
salutation receivers to have, in the following interface:

  interface Salutable {
public function getSalutationName();
  }

In this interface we have all we need to properly greet any entity: the
name we should use when doing the salutation.

Then we create the object which represents the world:

  class World implements Salutable {
public function getSalutationName() {
  return "World";
}
  }

Now we're missing a saluter, but we're not sure which way of greeting
would be appropiate, so we prefer to create an abstract saluter and leave
the child implementation to decide the appropiate greeting:

  abstract class Saluter {
abstract public function greet(Salutable $receiver);
  }

In our case we need a formal saluter as we should not disrespect the world
(saying "hey! wazzup world?" could be offensive), then:

  class FormalSaluter extends Saluter {
public function greet(Salutable $receiver) {
  echo "Hello " . $receiver->getSalutationName() . "\n";
}
  }

Finally we make our saluter greet the world:

  $saluter = new FormalSaluter();
  $world = new World();
  $saluter->greet($world);



Other things you should keep in mind:

* PHP's type hinting is preety limited, in this case we would like to
indicate that the name should be provided as a string but we can't. Maybe it
would be useful to use an object as a wrapper for native strings. EDIT: I
remembered while translating this that type hinting can only be used in
function parameters, therefore this point is useless.

* En this model it seems more appropiate that the saluter is an abstract
class, since salutation works one way, but, in the event salutations became
a two way trip, an interface would be more appropiate for the saluters.

* Here we're sending the salutation to the standard output, which is
acce

Re: [PHP] class usage

2006-09-29 Thread Martin Alterisio

2006/9/29, Ray Hauge <[EMAIL PROTECTED]>:


I think people have pretty much hit the nail on the head with OOP.  One
thing
that I would like to point out is that OOP isn't necessarily needed in
every
case.



Actually there's never a need to use OOP. As I said before OOP doesn't
provide anything in terms of functionality. The client will give a shit if
you use OOP, AOP, Modularity, Structural Programming, Functional Programming
or anything else there's out there. It's not about if we need it or not,
because we don't. It's about if we prefer to use OOP or not.

Real OOP is not just being able to code classes. Real OOP is about designing
useful classes.

There are times when making a class to abstract a certain

feature/process is a good idea, and there there are times where it can go
a
bit too far.  This is definitely a very simple example, but the usual
"Hello
World" script doesn't exactly need to be writen in a class structure.



Why not? If you're simply thinking of a class that does an echo, then there
is no point in using classes or not, but if you start thinking the problem
in terms of object abtraction there is a whole bunch of things that can be
shown with a simple "Hello World".

I usually try to ask myself this question when I'm designing something:


"What are the benefits of using OOP?"

If the answer is simply "To use OOP" then you're probably headed in the
wrong
direction, at which point I step back and look at the big picture again.



You're right: if you don't know how you can benefit with OOP then you
definetely shouldn't be using OOP.

In short, OOP is something to be used to your advantage, but if overused can

just cause unnecessary overhead and confusion (IMO)



I think *overused* is misleading, I would say *misused*.


Re: [PHP] Re: class usage

2006-09-29 Thread Martin Alterisio

2006/9/29, M.Sokolewicz <[EMAIL PROTECTED]>:


Well, you could say that there is no difference really. Classes are
mainly used as collections; They're a collection of functions (methods)
sharing a common goal/dataset/whatever.



That's a module, my friend, not a class:
http://en.wikipedia.org/wiki/Module_%28programming%29

Modularity was good, but OOP is better... IMO.


Re: [PHP] class usage

2006-09-29 Thread Martin Alterisio

2006/9/29, benifactor <[EMAIL PROTECTED]>:


ok, about five minutes ago i decided to learn classes and delve into php's
oop side.

what i came up with was this...

//start example code

class newsletter {
 function send ($email,$subject,$message) {
 if ($email) {
  echo("the following message was sent to: $email 
subject: $subject $message");
 }
 else {
  echo("failure");
 }
 }
}
$new = new newsletter();
$new->send("[EMAIL PROTECTED]", "test class", "test class worked, i have
passed and failed the test.");

//end code example



Why does your newsletter class have mailing logic?
Is your newsletter an abstraction of a newsletter or an abstraction of a
mailing system?
I would expect from a newsletter object the following:
* A way to indicate the format of the newsletter (plain text/html)
* That it asks me for the newsletter template
* A way to provide it with specific client data to create the newsletter for
that client
* A common interface to interact with mailing system abstraction (to send
the newsletter)

IMHO: this is not OOP, objects ARE NOT function repositories.

..and this seems to work fine, i could easily add  the mail function and

insert real variables into send() but what i don't understand is i could
also easily do this without a class... so i guess the real question is what
are some real life examples of class usage and why is it used as  opposed to
regular non oop? thank you for any input into the subject that you may have.



Whatever you do in OOP could have been easily done without. OOP doesn't add
anything in terms of functionality, on the contrary, OOP takes away your
freedom to do many things you can do without it, but that's the whole point
of it: the coder putting contraints on himself or other coders so that we
don't mess up.

But having only that is not real OOP. Real OOP is reusability on steroids.
If you code thinking how your objects could be used for something more that
what you're doing right now, you'll have your current problem solved and
future problems will be easier to solve.


[PHP] OOP Hello World

2006-09-28 Thread Martin Alterisio

What's up folks?

I just wanted to tell you about a thread that's going on in the spanish php
mailing list. A fellow software developer which had just started with OOP
was asking for "Hello World" examples using OOP. The examples of code he had
been doing was not that different from the usual Hello World example we all
know and love(?), so I thought he was missing the point of what was the
purpose of using OOP. This was my reply (I'll try to keep the translation as
accurate as possible):

I believe you have misunderstood what is the purpose of OOP, your objects
are not proper abstractions.

First and most important, you should define what is the problem to solve:
greet the world.
We build an abstraction of the problem and its main components: somebody who
greets and something to greet.
Here we're working with generalizations, since our main objective is to
build reusable objects. For that purpose is useful that our "saluter" could
be used to greet more than just the world.

Therefore we'll first define what kind of interaction we expect the
salutation receivers to have, in the following interface:

 interface Salutable {
   public function getSalutationName();
 }

In this interface we have all we need to properly greet any entity: the name
we should use when doing the salutation.

Then we create the object which represents the world:

 class World implements Salutable {
   public function getSalutationName() {
 return "World";
   }
 }

Now we're missing a saluter, but we're not sure which way of greeting would
be appropiate, so we prefer to create an abstract saluter and leave the
child implementation to decide the appropiate greeting:

 abstract class Saluter {
   abstract public function greet(Salutable $receiver);
 }

In our case we need a formal saluter as we should not disrespect the world
(saying "hey! wazzup world?" could be offensive), then:

 class FormalSaluter extends Saluter {
   public function greet(Salutable $receiver) {
 echo "Hello " . $receiver->getSalutationName() . "\n";
   }
 }

Finally we make our saluter greet the world:

 $saluter = new FormalSaluter();
 $world = new World();
 $saluter->greet($world);



Other things you should keep in mind:

* PHP's type hinting is preety limited, in this case we would like to
indicate that the name should be provided as a string but we can't. Maybe it
would be useful to use an object as a wrapper for native strings. EDIT: I
remembered while translating this that type hinting can only be used in
function parameters, therefore this point is useless.

* En this model it seems more appropiate that the saluter is an abstract
class, since salutation works one way, but, in the event salutations became
a two way trip, an interface would be more appropiate for the saluters.

* Here we're sending the salutation to the standard output, which is
acceptable in this case, but a more complex abstration would require us to
indicate where we should procede with the salutation, and we will have to
provide an abstraction for the possible salutation enviroments.

* A factory of saluters would be a nice feature.



That's it. If you find this interesting I'll try to keep up with the
translation of following posts.


Re: [PHP] How do i check if a variable is a reference or a copy?

2006-09-28 Thread Martin Alterisio

2006/9/28, Mathijs <[EMAIL PROTECTED]>:


Hello there,

Is there a way to check if a variable is passed by reference or if it is
just a copy. With something like is_copy or is_reference?

Thx in advance.



Is this part of the "I don't know if two vars reference the same object in
PHP4" dilemma?


Re: [PHP] array_sum($result)=100

2006-09-25 Thread Martin Alterisio

2006/9/25, Robin Vickery <[EMAIL PROTECTED]>:


On 24/09/06, Ahmad Al-Twaijiry <[EMAIL PROTECTED]> wrote:
> Hi everyone
>
> I have array of numbers and I want to get out of it a list of numbers
> that if I sum them it will be 100, here is my list (for example ) :
>
> $list = array(10,20,10,10,30,50,33,110,381,338,20,11,200,100);
>
>
> I want the result to be :
>
> $result = array( 10,20,10,10,50);
>
> as you can see in the array $result , if we array_sum($result) the
> result will be 100.
>
> is they any algorithm to do this ?

Ah, the Subset Sum Problem - this isn't school homework by any chance?



You're surely mistaken, there are many practical uses of the subset sum
problem in website development, like errr... shipping optimization!


Re: [PHP] Help converting C to PHP

2006-09-22 Thread Martin Alterisio

2006/9/22, Tom Atkinson <[EMAIL PROTECTED]>:


Martin Alterisio wrote:
> 2006/9/22, Rory Browne <[EMAIL PROTECTED]>:
>>
>> On 9/22/06, Kevin Waterson <[EMAIL PROTECTED]> wrote:
>> >
>> > This one time, at band camp, "Curt Zirzow" <[EMAIL PROTECTED]> wrote:
>> >
>> > > what about using:
>> > >   php.net/pi
>> > >
>> > > note the precision description.
>> > >
>> > > or are we talking about a different pi.
>> >
>> > The goal of the codegolf.com challenge is to print pi to 1000 places.
>> > The programmer to do it in the least keystrokes is the winner.
>>
>>
>> I personally don't think this is a very healthy contest. It discourages
>> comments, and use of whitespace to make code readable.
>>
>> I'd perfer a contest that rewarded code readability, and
maintainability
>> as
>> well as minimal keystrokes. After all you only enter the aforementioned
>> keystrokes once. Perhaps one like codegolf, with an enforced coding
style
>> (
>> eg KR Style, or GNU Style)
>>
>>
> I completely agree. This kind of contests do not provide any measure of
the
> good qualities of a programmer working as part of a team. The objectives
> ussualy end up being something of the sort: "let's see who can fit the
most
> in a for declaration".
>
> Anyway... as you say, it would be nice to have a contest that rewards
> readability and maintainability... but, how can we messure that
> qualities in
> this type of games? Should your code be praised by others and voted on?
Is
> that reliable? I think enforcing a coding style is too restrictive...
Also,
> how do we measure the declarativity of var and function names?
>

The value of these games is that they give you interesting problems to
solve without forcing you to maintain the code. That's the entire point.
It's exactly the sort of thing that's fun to write when you have to make
a living from your code the rest of the time. If you want to write
quality software in your free time then you start/join an FOSS project
and put the code to good use.

Nobody is claiming that this is a good way to write code or a good way
to learn PHP, it's just for fun.



You're right, it's just for fun but... they could still be fun and be
useful. These kind of games could easily be used for education and training.
We all know that the quest/mob grinding factor can be very addictive, why
don't use all that energy for the good? You could still learn how to do a
good job while having fun...


Re: [PHP] Help converting C to PHP

2006-09-22 Thread Martin Alterisio

2006/9/22, Rory Browne <[EMAIL PROTECTED]>:


On 9/22/06, Kevin Waterson <[EMAIL PROTECTED]> wrote:
>
> This one time, at band camp, "Curt Zirzow" <[EMAIL PROTECTED]> wrote:
>
> > what about using:
> >   php.net/pi
> >
> > note the precision description.
> >
> > or are we talking about a different pi.
>
> The goal of the codegolf.com challenge is to print pi to 1000 places.
> The programmer to do it in the least keystrokes is the winner.


I personally don't think this is a very healthy contest. It discourages
comments, and use of whitespace to make code readable.

I'd perfer a contest that rewarded code readability, and maintainability
as
well as minimal keystrokes. After all you only enter the aforementioned
keystrokes once. Perhaps one like codegolf, with an enforced coding style
(
eg KR Style, or GNU Style)



I completely agree. This kind of contests do not provide any measure of the
good qualities of a programmer working as part of a team. The objectives
ussualy end up being something of the sort: "let's see who can fit the most
in a for declaration".

Anyway... as you say, it would be nice to have a contest that rewards
readability and maintainability... but, how can we messure that qualities in
this type of games? Should your code be praised by others and voted on? Is
that reliable? I think enforcing a coding style is too restrictive... Also,
how do we measure the declarativity of var and function names?


Re: [PHP] Iteration through letter

2006-09-15 Thread Martin Alterisio

2006/9/14, Norbert Wenzel <[EMAIL PROTECTED]>:


Hi,

just for fun I tried the following code:


for($letter = 'A'; $letter <= 'Z'; ++$letter) {
echo($letter . ' ');
}


What surprised me was the output, which looked like this:

A B C [...] Y Z AA AB AC [...] YY YZ

I don't have any idea how these letters get printed out, so I'd
appreciate any guesses or explanations.

thanks,
Norbert

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



http://marc.theaimsgroup.com/?t=11494428112


Re: [PHP] Error Handling Library?

2006-08-31 Thread Martin Alterisio

I'm curious, what features are you looking for in an error handling library?

2006/8/31, Jay Paulson <[EMAIL PROTECTED]>:


I've been doing some research and was wondering if anyone out there has
written a library for error handling?  I haven't found anything as of yet
but would love to hear suggestions!

Thanks!

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




Re: [PHP] Mixing sprintf and mysql_real_escape_string

2006-08-07 Thread Martin Alterisio

2006/8/7, Peter Lauri <[EMAIL PROTECTED]>:


I should maybe add that the data actually comes from a form:

mysql_query(sprintf("INSERT INTO table (value1, value2) VALUES (1,
'%s')", mysql_real_escape_string($_POST['formvalue'])));

And when I have ' in the field, it will insert \' into the database in
pure
form. If I do this it will add just ' (with the $_POST['formvalue']="'";

mysql_query(sprintf("INSERT INTO table (value1, value2) VALUES (1,
'%s')", $_POST['formvalue']));

Something that we are missing out here?



My guess: magic_quotes_gpc is enabled where you're running the script.
Therefore slashes are already present in the data from the form post.

-Original Message-

From: Richard Lynch [mailto:[EMAIL PROTECTED]
Sent: Tuesday, August 08, 2006 5:54 AM
To: Peter Lauri
Cc: php-general@lists.php.net
Subject: Re: [PHP] Mixing sprintf and mysql_real_escape_string

On Mon, August 7, 2006 12:35 pm, Peter Lauri wrote:
> I get strange output if I combine sprintf and
> mysql_real_escape_string. If I
> do this the resulting into the database is \' not ' as I want.
>
> mysql_query(sprintf("INSERT INTO table (value1, value2) VALUES (1,
> '%s')",
> mysql_real_escape_string(" ' ")));
>
> Should this be like this? Do the sprintf already add slashes or
> something?

mysql_real_escape_string(" ' ") will yield:   \'

This is because the ' is a "special" character to the MySQL parser --
It indicates the beginning and end of character-based data.

So if you want ' to *BE* part of your data, it needs to be escaped
with \ in front of ' and that tells MySQL, "Yo, this apostrophe is
data, not a delimiter".

sprintf should simply output:
INSERT INTO table (value1, value2) VALUES(1, ' \' ')
because is just slams the output into the %s part.

mysql_query() sends that whole thing off to MySQL.

When MySQL "reads" the SQL statement, and tries to figure out what to
do, it "sees" that line.

Because of the \' in there, it knows that the middle ' is not the end
of the string, but is part of the data.

So what MySQL actually stores for value2 is just:
'

MySQL does *NOT* store \' for that data -- The \ part of \' gets
"eaten" by MySQL parser as it works through the SQL statement, and it
just turns into plain old ' to get stored on the hard drive.

If you think it did store that, then either you didn't tell us the
correct thing for what you did, or your test for what MySQL stored is
flawed.

The usual suspect, in PHP, for this problem, is that the data is
coming from GET/POST (or COOKIES) and you have Magic Quotes turned
"ON" and the data is already getting escaped by
http://php.net/addslashes, and then you escape it *AGAIN* with
mysql_real_escape_string.

mysql_real_escape_string is better than addslashes (and/or Magic
Quotes) so turn off Magic Quotes and keep the mysql_real_escape_string
bit.

--
Like Music?
http://l-i-e.com/artists.htm

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




Re: [PHP] How to get rid off empty elements of an array?

2006-08-07 Thread Martin Alterisio

2006/8/7, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:


Hi to all!

I have a form with 6 text fields where visitor has to enter product serial
number (same type data). he has to enter AT LEAST ONE.

for ($i=0; $i<6; $i++)
{
echo '';
}

After the form is submitted I'm getting an array

Array
(
[0] => abc123
[1] => ddd111
[2] => poi987
[3] =>
[4] =>
[5] =>
)

Now, I need to get rid off empty elements of the array, to get this:

Array
(
[0] => abc123
[1] => ddd111
[2] => poi987
)

To do that I tried:
foreach ($PSN as $value)
{
   if (!empty($value))$PSN_New[] = $value;
}
but every time I'm getting one additional element of the array:

I tried
foreach ($PSN as $value)
{
   if ($value != '')$PSN_New[] = $value;
}
too - same result.

Array
(
[0] => abc123
[1] => ddd111
[2] => poi987
[3] =>
)

No space or anything else is "entered" in 4th field.

What I'm doing wrong?

Thanks for any help.

-afan

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



There are probably some whitespaces in the elements which refuse to be
deleted.
Also consider using array_filter() instead of looping through the array
(used without a callback function filter all elements which evaluate to
boolean false).


Re: [PHP] Re: PHP Frameworks - Opinion

2006-08-06 Thread Martin Alterisio

2006/8/4, Manuel Lemos <[EMAIL PROTECTED]>:


Hello,

on 08/03/2006 05:18 PM Martin Alterisio said the following:
>> Anyway, you may want to read this more in depth reflection of the state
>> of the PHP framework world and recommendations on how to pick what
suits
>> best for you:
>>
>> http://www.phpclasses.org/blog/post/52-Recommended-PHP-frameworks.html
>
>
> Sorry to intrude with my usual obnoxious behaviour, but this is starting
to
> affect my self-esteem (what's left of it). Am I the only one who has a
> really hard time reading the blog posts in phpclasses.org? Everytime a
> reference to this blog is posted I lose track of the discussion, because
I
> can't really grasp what Lemos is talking about.
>
> I'd like to make some some constructive criticism, not just to Lemos but
to
> the community in general, since I think many of us need to improve our
> writing skills:
>
> 1 - Don't make lng boooring posts.

This blog in reality is the site monthly announcement newsletter. Some
months there is more to tell than in others. I usually put a list of
contents when the post is about many subjects.



Then maybe you should consider making it a _weekly_ announcement newsletter,
'cause some of those posts are really really too long to digest in only one
shot.


2 - Get to the point. Introduction are great when they are not two pages
> long.

I don't know what you mean by introduction. Usually there is a summary
that goes in the RSS feed that is no longer than 3 or 4 paragraphs.



I mean all the things you need to say before actually getting into what you
want to talk about. Just take for example the post about "recommend php
framework", look how much you have to read before actually get any info
relating directly to php frameworks. Is true that there are many things to
say before about frameworks hype, but couldn't it be explained in less
words?


3 - Stick to the topic. Or use appropiate titles.

> 4 - If the topic is inherently long, use distinguishable headers and
> subheaders. It's a pain in the ass to read a 5 pages long article that
> looks
> the same everywhere, with no easy way to know what is the subtopic of
what
> are you reading now.

As I said, these posts often cover many topics. It may not seem by topic
sections use titles. The problem is that this newsletter posts used to
go by e-mail to the site subscribers in plain text, so there was no way
to format titles.



I was unaware of that, I understand now. It's really a pain in the ass to
format a text only email for proper reading even more if the same text
has to be used in a website.

Anyway, now that you mentioned it I applied an additional regular

expression to add title formatting when presenting it in the site. Just
let me know if it looks ok now.



Yeah, I saw that. I believe it's a little bit better now.


5 - Don't talk so much about your life! You can always make another blog
> for
> that... Unless your personal experience can bring an unique insight of
the
> point you're trying to make.

I suppose you may be talking about other peoples blogs. Personal blogs
are supposed to be personal. This is the PHPClasses site blog. Usually
it covers matters about the site developments and matters of interest to
the site users. It does not talk about my life. It may talk about my
experience when it is relevant to the post topic.



Generally speaking, yes, I'm talking about other peoples blogs. I'm sick
tired of all the holy crusades out there, specially when it comes to
Web2.0evangelists. You may have not noticed it but somewhere here or
there you let
your subconcious write for you, specially on the topic of Web2.0 (I used the
term twice already, please stop me before I have to pay royalties to
O'reilly). It may be just an adjective, but that's all it takes to make a
mildly objetive point of view turn into a completely subjective point of
view.

Just check your article about "is php ready for ..." *that thing I said
before*, and you'll see that how, without noticing it, personal feelings
tend to appear and change the article completely. Probably that's what made
you write so much about how you believe phpclasses.org is a *that term*
enabled site, and why. Was all that really necesary for the purpose of the
article? Or you were just uncounciously trying to prove something to all
those lamers out there? Does it really matter if your site is "in" or "out"?
We are not fashion designers...


Re: [PHP] Re: PHP Frameworks - Opinion

2006-08-03 Thread Martin Alterisio

2006/8/3, Manuel Lemos <[EMAIL PROTECTED]>:


Hello,

on 08/01/2006 01:35 PM Gabe said the following:
> What's the common consensus as to a solid PHP framework to use for
> application development?  There seems to be a number of them out there,
> but I'm not sure which one's are the most robust, actively developed,
> secure, etc etc.
>
> Thoughts?

There is no common consense. PHP development is not very well organized,
like for instance in the Java world where several vendors can provide
their own implementations of the same specification. This makes possible
to use the same framework API from whatever vendor you prefer.

In the PHP world all frameworks are incompatible, even when they attempt
to implement similar feature sets.

Anyway, you may want to read this more in depth reflection of the state
of the PHP framework world and recommendations on how to pick what suits
best for you:

http://www.phpclasses.org/blog/post/52-Recommended-PHP-frameworks.html



Sorry to intrude with my usual obnoxious behaviour, but this is starting to
affect my self-esteem (what's left of it). Am I the only one who has a
really hard time reading the blog posts in phpclasses.org? Everytime a
reference to this blog is posted I lose track of the discussion, because I
can't really grasp what Lemos is talking about.

I'd like to make some some constructive criticism, not just to Lemos but to
the community in general, since I think many of us need to improve our
writing skills:

1 - Don't make lng boooring posts.

2 - Get to the point. Introduction are great when they are not two pages
long.

3 - Stick to the topic. Or use appropiate titles.

4 - If the topic is inherently long, use distinguishable headers and
subheaders. It's a pain in the ass to read a 5 pages long article that looks
the same everywhere, with no easy way to know what is the subtopic of what
are you reading now.

5 - Don't talk so much about your life! You can always make another blog for
that... Unless your personal experience can bring an unique insight of the
point you're trying to make.

That's all folks.

--


Regards,
Manuel Lemos

Metastorage - Data object relational mapping layer generator
http://www.metastorage.net/

PHP Classes - Free ready to use OOP components written in PHP
http://www.phpclasses.org/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




[PHP] PHP Love Letter

2006-07-18 Thread Martin Alterisio

Been quiet too much...

*This time, I seriously advise against running this piece of code unless you
know what you're doing*

Enjoy...

---



 Love Letter


acquaintances)) {
?>
 Dear name?>,
 I really enjoy your company and I would love to meet you again.
 I had a lot of fun last time and I can't wait to get to know you
better.
 Yours sincerely, name?>
intimateFriends)) {
?>
 Dear nickName?>,
 All I wanted to say is how lucky I'm to have met you, to have you by my
side.
 I can't think of a world without you. I can't possibly thank you enough
for all the happy moments you gave me.
 Yours, nickName
boyfriend) && $her->boyfriend == $me) {
   $loversNicknames = array('Honey', 'Sweetie', 'Baby', 'Princess',
'Queen', 'Love', 'Sunshine');
?>
 My ,
 I couldn't wait to tell you how much I love you.
 You're the only one, the reason why I'm on this world. The only place I
wanna be is besides you.
 Missing you already, your Love
husband) && $her->husband== $me) {
?>
 I love you.
 PS: What's for dinner?
 /dev/null');
   // Now, get your lazy ass out there
   exit;
 }
?>




[PHP] Re: Sad PHP Poem

2006-06-30 Thread Martin Alterisio

2006/6/26, Martin Alterisio <[EMAIL PROTECTED]>:




A sad poem of an algorithm where solitude brought excessive use of cpu
cycles and memory allocation for redundant data (it copied over and over
again the same image till all memory was filled with it)

--

$timeWaiting = 0;
while (!$you->near($me)) {
  $me->thinkAbout($you);

  switch (true) {
case $timeWaiting < 5:
  $me->wait($you);
  break;

case $timeWaiting < 10:
  $me->worry();
  break;

case $timeWaiting < 20:
  $me->lookFor($you) ;
  break;

case $timeWaiting < 40:
  $me->worry();
   $me->lookFor($you) ;
  break;

case $timeWaiting < 80:
  $me->worry();
   $me->cry();
   $me->lookFor($you) ;
   $me->lookFor($you) ;
   $me->lookFor($you) ;
  break;

case $timeWaiting < 160:
  $me->worry();
   $me->cry();
   $me->drink();
   $me->lookFor($you) ;
   $me->lookFor($you) ;
   $me->lookFor($you) ;
  $me->thinkAbout($you);
   $me->thinkAbout($you);
   $me->cry();
   $me->lookFor($you) ;
   $me->lookFor($you) ;
   $me->drink();
   $me->drink();
   break;

default:
  throw new CantLiveWithoutYou();
  die("alone");
  }

  $timeWaiting++;
}

$me->happy = true;

--

I hope you enjoyed the poem and the fact that I didn't ask you to fix it
or find the bug in it =D

PD: Run in your web server at your own risk.





I guy over here completed the code to allow its execution
http://devzone.zend.com/node/view/id/576 (see the comments).

---

Then, I having trouble with this code, would you be so kind to look at it:


// He says he did it, but he's crazy. Who knows...
$poem->author = new Person("Martin Alterisio");
// TO DO: Person might not be the proper class here. Check that.

foreach (Person::$all as $you) {
 if ($you->like($poem)) {
   $poem->author->thank($you);
 } else {
   // TO DO: Spread the geekness



   // On second thought, maybe that's not a good idea
 }
}


That's all folks. Coming up next: an innovative realistic soccer simulation
game: "Fix the World Cup". Everything from bribing a referee to fixing the
team sorting. Do you lack the morality to make your team the world champion
by any means necessary? Take this chance to prove it!  (just joking...
really but it would be a good game, wouldn't it?)


Re: [PHP] working on a template system...

2006-06-28 Thread Martin Alterisio

2006/6/28, Jon Anderson <[EMAIL PROTECTED]>:


I really don't understand why people have such disregard for PHP as a
template system... I'm not saying one way is better or worse (it's
really a matter of preference), just that the PHP way isn't implicitly
bad or messy...

/* The Smarty way */
$smarty->assign('display_variable',$display_variable);
...
{* template *}

  {foreach key=key item=var from=$display_variable}
{$key}{$var}
  {/foreach}


/* The PHP way */

   $var) { ?>

  


Is it really *that* bad?

jon

Martin Alterisio wrote:
> 2006/6/28, Robert Cummings <[EMAIL PROTECTED]>:
>>
>> On Wed, 2006-06-28 at 07:32, Martin Marques wrote:
>> > On Wed, 28 Jun 2006, Ligaya Turmelle wrote:
>> >
>> > > Martin Marques wrote:
>> > >> Why not try to use one of the template systems that already exist?
>> > >> HTML_Template_IT, Smarty, etc.
>> > >>
>> > > Or just use PHP...
>> >
>> > Because it's a mess.
>>
>> Agreed. Mr. nail, come meet Mr. hammer :B
>
>
> And keep Mr. hammer away from Mr. finger

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Have you (all of you questioning the use of templates) ever worked in a
project with more than one developer, where part of the team ARE NOT coders?
WE understand code, but that's not the case for everyone else. Graphic
designers don't like code, they even don't like html for crying out loud (I
think they have a good point there btw). Editor, writers, marketing people
they all give a damn about php and the like, but, still they need or want to
mess up with how things look like, and they really don't like the idea of
having to wait two laboral days to change the fricking color of a link, or
have an newsletter email typo corrected. They need templates, they love
templates. Just put it in dreamweaver (or the like), fix the look, upload
and we're back on business, why the hell should I have to call the damn
coder?

The net has been developed by amateurs long enough (no offense, just
introspective). If we are to became more professional, we'll need the right
tools, templates is just one of those tools.


Re: [PHP] working on a template system...

2006-06-28 Thread Martin Alterisio

2006/6/28, Robert Cummings <[EMAIL PROTECTED]>:


On Wed, 2006-06-28 at 07:32, Martin Marques wrote:
> On Wed, 28 Jun 2006, Ligaya Turmelle wrote:
>
> > Martin Marques wrote:
> >> Why not try to use one of the template systems that already exist?
> >> HTML_Template_IT, Smarty, etc.
> >>
> > Or just use PHP...
>
> Because it's a mess.

Agreed. Mr. nail, come meet Mr. hammer :B



And keep Mr. hammer away from Mr. finger

Cheers,

Rob.
--
..
| InterJinn Application Framework - http://www.interjinn.com |
::
| An application and templating framework for PHP. Boasting  |
| a powerful, scalable system for accessing system services  |
| such as forms, properties, sessions, and caches. InterJinn |
| also provides an extremely flexible architecture for   |
| creating re-usable components quickly and easily.  |
`'

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




Re: [PHP] Sad PHP Poem

2006-06-25 Thread Martin Alterisio

2006/6/26, Ligaya Turmelle <[EMAIL PROTECTED]>:


Martin Alterisio wrote:
> 
>
> A sad poem of an algorithm where solitude brought excessive use of cpu
> cycles and memory allocation for redundant data (it copied over and over
> again the same image till all memory was filled with it)
>
> --
>
> $timeWaiting = 0;
> while (!$you->near($me)) {
>  $me->thinkAbout($you);
>
>  switch (true) {
>case $timeWaiting < 5:
>  $me->wait($you);
>  break;
>
>case $timeWaiting < 10:
>  $me->worry();
>  break;
>
>case $timeWaiting < 20:
>  $me->lookFor($you);
>  break;
>
>case $timeWaiting < 40:
>  $me->worry();
>   $me->lookFor($you);
>  break;
>
>case $timeWaiting < 80:
>  $me->worry();
>   $me->cry();
>   $me->lookFor($you);
>   $me->lookFor($you);
>   $me->lookFor($you);
>  break;
>
>case $timeWaiting < 160:
>  $me->worry();
>   $me->cry();
>   $me->drink();
>   $me->lookFor($you);
>   $me->lookFor($you);
>   $me->lookFor($you);
>  $me->thinkAbout($you);
>  $me->thinkAbout($you);
>  $me->cry();
>   $me->lookFor($you);
>   $me->lookFor($you);
>   $me->drink();
>   $me->drink();
>  break;
>
>default:
>  throw new CantLiveWithoutYou();
>  die("alone");
>  }
>
>  $timeWaiting++;
> }
>
> $me->happy = true;
>
> --
>
> I hope you enjoyed the poem and the fact that I didn't ask you to fix it
or
> find the bug in it =D
>
> PD: Run in your web server at your own risk.
>
> 
>
See we do have a softer side.  Outstanding!



I was a hard man till she threw me a ImNotSoSureAnymore exception =S

PD: I'm on fire today, maybe AJAX and the greek muses are behind my
inspiration

--


life is a game... so have fun.





[PHP] Sad PHP Poem

2006-06-25 Thread Martin Alterisio



A sad poem of an algorithm where solitude brought excessive use of cpu
cycles and memory allocation for redundant data (it copied over and over
again the same image till all memory was filled with it)

--

$timeWaiting = 0;
while (!$you->near($me)) {
 $me->thinkAbout($you);

 switch (true) {
   case $timeWaiting < 5:
 $me->wait($you);
 break;

   case $timeWaiting < 10:
 $me->worry();
 break;

   case $timeWaiting < 20:
 $me->lookFor($you);
 break;

   case $timeWaiting < 40:
 $me->worry();
  $me->lookFor($you);
 break;

   case $timeWaiting < 80:
 $me->worry();
  $me->cry();
  $me->lookFor($you);
  $me->lookFor($you);
  $me->lookFor($you);
 break;

   case $timeWaiting < 160:
 $me->worry();
  $me->cry();
  $me->drink();
  $me->lookFor($you);
  $me->lookFor($you);
  $me->lookFor($you);
 $me->thinkAbout($you);
 $me->thinkAbout($you);
 $me->cry();
  $me->lookFor($you);
  $me->lookFor($you);
  $me->drink();
  $me->drink();
 break;

   default:
 throw new CantLiveWithoutYou();
 die("alone");
 }

 $timeWaiting++;
}

$me->happy = true;

--

I hope you enjoyed the poem and the fact that I didn't ask you to fix it or
find the bug in it =D

PD: Run in your web server at your own risk.




Re: [PHP] Get rid of line breaks

2006-06-18 Thread Martin Alterisio

2006/6/18, Peter Lauri <[EMAIL PROTECTED]>:


Best group member,



I have a variable $content that is taken from a database. It contains line
breaks and the $content will be posted with line breaks.



I need to use this to insert this into a JavaScript function:



$output = 'writeRichText(\'rte1\', \''.$content.'\', 400, 200, true,
false);';



What is actually outputted is:



writeRichText('rte1', 'a

b', 400, 200, true, false);



Because it is on different lines in the HTML the javascript function will
not be called correct.



So can I remove all line breaks in a variable with a function call?



Dream: $content = stripLineBreaks($content);



I read the manual, but without luck.



Thanks in advance.




Check out http://php.net/addcslashes
maybe that will do the trick. If that doesn't work, you should try to
replace the line break character with the corresponding escape sequence.


Re: [PHP] How to run one php app from another? RECAP

2006-06-16 Thread Martin Alterisio

2006/6/16, tedd <[EMAIL PROTECTED]>:


Hi gang:

So, there is NOT a way for one running php-application to call another and
have it run while having the parent quit?

For example, program "a" runs and presents the user with a web page. The
user responds in some fashion (i.e., enters text) and clicks "Submit".
Then the application analyzes the data and chooses to run application "d"
from a list of possible applications. NOTE: This is different than the user
clicking a link to run application "d". It is application "a" that's making
the choice to run "d", not the user. Can this be done?

Let me recap the solutions offered:

1. There was the suggestion to use includes(). However, includes simply
adds code into the current application. It does not terminate the parent nor
start another application. It simply bloats the parent.

2. There was the suggestion to use ob_start with header("Location: ...");
and finish with ob_flush. However, the parent application never shows itself
-- the process simply cascades down to the end application. In this case,
the parent (as in the example above) would never show the user the text-box
to enter his/her text.

3. There was the suggestion to use js, which works and is the way I'm
doing it now. However, I wanted a php solution.

So, what say you fine php people, can anyone give me an example of a php
application running (i.e., calling) another? I suspect that php can't, but
I don't know why -- it doesn't seem logical. Is this one of those stateless
problematic thingies, or what?

Thanks.

tedd
--


http://sperling.com  http://ancientstones.com  http://earthstones.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



You can fork a new process a run the other script in the child process. But
forking is not always available so I also use another approach: emulate a
web page request through sockets or curl to the script I want to run.


Re: [PHP] progress monitor in php

2006-06-15 Thread Martin Alterisio

2006/6/15, weetat <[EMAIL PROTECTED]>:


Hi all ,

   I was using PEAR:HTTP_Upload to upload file in php 4.3.2.
   Is ok , however i need to display some sort of progress monitor to
the user because some file is very large and took some times to upload.
I need to inform the users to uploading is in progress.

I have search google ,and found megaupload , however the problem of
megaupload is the filename is rubbish, i need the filename of uploaded
file because the file is xml , need to convert data from xml to database.

Anybody have any ideas ? Or have any another php upload progress monitor ?

Thanks

- weetat

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Maybe this will help:
http://uber-uploader.sourceforge.net/


Re: [PHP] mysql + PHP

2006-06-15 Thread Martin Alterisio

2006/6/15, weetat <[EMAIL PROTECTED]>:


Hi all,

   I have SQL query , for example , Select country , name from
tbl_chassis order by country.

  The problem of the sql statement is that , if there are empty value in
country field , it be sorted first .

How to do sorting the empty value last
? I can cp() function to do this ? or any mysql function to use?

Thanks
- weetat

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Maybe this will do the trick:

select country, name
 from tbl_chassis
order by country = '', country


Re: [PHP] Skip first 4 array values

2006-06-09 Thread Martin Alterisio

2006/6/9, Jonas Rosling <[EMAIL PROTECTED]>:


Is there any way you can skip for example the first 4 array
values/posisions
in an array no matter how many values it contains?

Thanks // Jonas

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Maybe: array_slice()
http://www.php.net/manual/en/function.array-slice.php


Re: [PHP] generating/transforming HTML so that it 'works' in a flash file

2006-06-07 Thread Martin Alterisio

2006/6/7, Jochem Maas <[EMAIL PROTECTED]>:


hi people,

I've been STFW till I'm blue in the face (so lack of oxygen might be
problem atm) but can't find any [decent] info on generating/transforming
existing
HTML so thats it's compatible with the subset of tags that are supported
by Flash (apparently Flash has the ability to show something that
resembles
HTML in certain visual controls - I don't flash, I'm just responsible for
supplying XML feeds that the flash site/file in question can consume).

so the question does any know of a reliable resource on this subject
and/or
some code nugget that is capable of generating/transforming (x)HTML into
the cruft that Flash is capable of displaying?

any feedback is welcome (apart from 'STFW' - I'm already doing that :-P)

rgds,
Jochem

ps - my server side stuff is all php (so I need to have an HTML
'converter'
written in php too [preferably]) before someone hits me with the 'what
does
this has to do with php' response.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Have you read the following?
http://livedocs.macromedia.com/flash/mx2004/main_7_2/1027.html
http://livedocs.macromedia.com/flash/mx2004/main_7_2/1014.html


Re: [PHP] When is "z" != "z" ?

2006-06-06 Thread Martin Alterisio

2006/6/6, Robert Cummings <[EMAIL PROTECTED]>:


On Tue, 2006-06-06 at 14:31, Martin Alterisio wrote:
> 2006/6/6, Robert Cummings <[EMAIL PROTECTED]>:
> >
> > On Tue, 2006-06-06 at 14:06, Martin Alterisio wrote:
> > > 2006/6/6, Robert Cummings <[EMAIL PROTECTED]>:
> > > >
> > > > > > You must have missed this post:
> > > > > >
> > > > > >
http://marc.theaimsgroup.com/?l=php-general&m=114945456908350&w=2
> > > > > >
> > > > > >
> > > > > Yes, I haven't read that post. That algorithm has an error, an
> > overflow
> > > > on a
> > > > > signed char, and that's implementation issue not a design issue.
> > > >
> > > > Actually it's a design issue. C uses a numeric datatype that is
bound
> > by
> > > > a specific number of bits. It could just have well have been
designed
> > > > with a numeric datatype that had arbitrary length. The design
decision
> > > > was made to keep it close to the machine. However, the point I was
> > > > making is that dealing with fringe cases is a necessity when you
want
> > to
> > > > ensure your code is robust.
> > >
> > >
> > > I haven't thought this carefully, you're right to point that is a
design
> > > issue since compilers and interpreters have to take into account the
> > actual
> > > data representation in the design stage. Still, an overload is an
known
> > > issue and that can be caught easily. If you assume that the ++ and
> > > comparison operator can be used with any type of object in a for
loop,
> > and
> > > they don't follow the expected contrains an iterator shoud have then
the
> > > problem will be less apparent, as the issue is not considered a
misuse
> > but a
> > > normal function of the data type.
> >
> > So there you go, by your own words, knowing the way the system works
and
> > the edge cases is integral to proper use of the language. Thus when
> > 'z'++ == 'aa' the semantics while not necessarily ubiquitous, fall
under
> > the language's well defined modus operandi :)
>
> You lost me there. Can you explain it a little bit further?

You said:

"Still, an overload is an known issue and that can be caught
 easily."

It follows that you need information about the overload to handle it.

It is a known issue in PHP that incrementing 'z' by 1 produces 'aa'

It follows that knowing that 'z' incremented by 1 produces 'aa' can be
caught easily.

It follows that if it can be caught easily, it can be handled easily.

Thus it finally follows your own words:

"as the issue is not considered a misuse but a normal function
 of the data type"

Normal in PHP is exactly the behaviour that PHP deemed many years ago
for it to follow.



Thanks, I got it now.

What I meant as "known issue" is that the program is notified of the
occurrence of such problem. When the 'z' is incremented into 'aa' you're
stepping back in the sequence order but nothing is said or notified in any
way. The coder who explicitly wants to use such feature may handle the issue
without a problem, but when you work on the basis that you can receive any
kind of sequence, range, or iterator you can't know for sure that this
happens. Consider this example:

function orderedSequence($start, $end) {
   $orderedSequence = array();
   for ($i = $start; $i <= $end; $i++) {
   $orderedSequence[] = $i;
   }
   return $orderedSequence;
}

Supposedly this function would return an ordered sequence of objects, which
implement iteration, between $start and $end. Under the mentioned
circumstances the function would fail to return an ordered sequence. Still,
this kind of "generic" behaviour it something that isn't useful in PHP,
since there isn't operator overloading. Anyway PHP5 has some features that
point that generics will be used (correct if i'm wrong here, that's what I
thought when I saw iterators in the SPL) and I think that we won't be able
to use native operators to create proper iterators on strings with the
current functionality assigned to them.

Well, my arguments are starting to sound much more like ranting that
anything else. Sorry if they weren't appropiate.


Re: [PHP] When is "z" != "z" ?

2006-06-06 Thread Martin Alterisio

2006/6/6, Robert Cummings <[EMAIL PROTECTED]>:


On Tue, 2006-06-06 at 14:06, Martin Alterisio wrote:
> 2006/6/6, Robert Cummings <[EMAIL PROTECTED]>:
> >
> > > > You must have missed this post:
> > > >
> > > > http://marc.theaimsgroup.com/?l=php-general&m=114945456908350&w=2
> > > >
> > > >
> > > Yes, I haven't read that post. That algorithm has an error, an
overflow
> > on a
> > > signed char, and that's implementation issue not a design issue.
> >
> > Actually it's a design issue. C uses a numeric datatype that is bound
by
> > a specific number of bits. It could just have well have been designed
> > with a numeric datatype that had arbitrary length. The design decision
> > was made to keep it close to the machine. However, the point I was
> > making is that dealing with fringe cases is a necessity when you want
to
> > ensure your code is robust.
>
>
> I haven't thought this carefully, you're right to point that is a design
> issue since compilers and interpreters have to take into account the
actual
> data representation in the design stage. Still, an overload is an known
> issue and that can be caught easily. If you assume that the ++ and
> comparison operator can be used with any type of object in a for loop,
and
> they don't follow the expected contrains an iterator shoud have then the
> problem will be less apparent, as the issue is not considered a misuse
but a
> normal function of the data type.

So there you go, by your own words, knowing the way the system works and
the edge cases is integral to proper use of the language. Thus when
'z'++ == 'aa' the semantics while not necessarily ubiquitous, fall under
the language's well defined modus operandi :)



You lost me there. Can you explain it a little bit further?


Re: [PHP] When is "z" != "z" ?

2006-06-06 Thread Martin Alterisio

2006/6/6, tedd <[EMAIL PROTECTED]>:


If php is supposed to be open source, doesn't that mean that people can
voice their opinion on what they observe and expect?



I second that. I believe being open-source doesn't mean "Yay, it's free!"
but "Cool, someone is listening to us!"


Re: [PHP] When is "z" != "z" ?

2006-06-06 Thread Martin Alterisio

2006/6/6, Robert Cummings <[EMAIL PROTECTED]>:


On Tue, 2006-06-06 at 13:11, Martin Alterisio wrote:
> 2006/6/6, Robert Cummings <[EMAIL PROTECTED]>:
> >
> > On Tue, 2006-06-06 at 09:46, Martin Alterisio wrote:
> > > 2006/6/6, Robert Cummings <[EMAIL PROTECTED]>:
> > >
> > > > In C++ they do leave it to the coder, and well, we all know what a
> > mess
> > > > it can be deciphering overloaded operators in C++ (or maybe we ALL
> > > > don't). At any rate, the PHP overlords made a choice, and IMHO the
> > best
> > > > choice. For such a fringe issue I don't see what the argument is
all
> > > > about. If you want the functionality you get in C by incrementing
a
> > > > char, then use the chr() function on an integer.
> > > >
> > > >
> > > You're right about ++ operator not to be considered a math operator,
my
> > > mistake. What I should have said is that the usual connotation and
> > expected
> > > behaviour of ++ and the comparison operators is to give iteration
> > > capabilities to a certain data type, as used in a for statement. For
> > that to
> > > happen certain constrains must be true for these operators, one of
them
> > > being: any < ++any, which is not true for the way these operators
behave
> > in
> > > php.
> >
> > You must have missed this post:
> >
> > http://marc.theaimsgroup.com/?l=php-general&m=114945456908350&w=2
> >
> >
> Yes, I haven't read that post. That algorithm has an error, an overflow
on a
> signed char, and that's implementation issue not a design issue.

Actually it's a design issue. C uses a numeric datatype that is bound by
a specific number of bits. It could just have well have been designed
with a numeric datatype that had arbitrary length. The design decision
was made to keep it close to the machine. However, the point I was
making is that dealing with fringe cases is a necessity when you want to
ensure your code is robust.



I haven't thought this carefully, you're right to point that is a design
issue since compilers and interpreters have to take into account the actual
data representation in the design stage. Still, an overload is an known
issue and that can be caught easily. If you assume that the ++ and
comparison operator can be used with any type of object in a for loop, and
they don't follow the expected contrains an iterator shoud have then the
problem will be less apparent, as the issue is not considered a misuse but a
normal function of the data type.


Re: [PHP] When is "z" != "z" ?

2006-06-06 Thread Martin Alterisio

2006/6/6, Robert Cummings <[EMAIL PROTECTED]>:


On Tue, 2006-06-06 at 09:46, Martin Alterisio wrote:
> 2006/6/6, Robert Cummings <[EMAIL PROTECTED]>:
>
> > In C++ they do leave it to the coder, and well, we all know what a
mess
> > it can be deciphering overloaded operators in C++ (or maybe we ALL
> > don't). At any rate, the PHP overlords made a choice, and IMHO the
best
> > choice. For such a fringe issue I don't see what the argument is all
> > about. If you want the functionality you get in C by incrementing a
> > char, then use the chr() function on an integer.
> >
> >
> You're right about ++ operator not to be considered a math operator, my
> mistake. What I should have said is that the usual connotation and
expected
> behaviour of ++ and the comparison operators is to give iteration
> capabilities to a certain data type, as used in a for statement. For
that to
> happen certain constrains must be true for these operators, one of them
> being: any < ++any, which is not true for the way these operators behave
in
> php.

You must have missed this post:

http://marc.theaimsgroup.com/?l=php-general&m=114945456908350&w=2



Yes, I haven't read that post. That algorithm has an error, an overflow on a
signed char, and that's implementation issue not a design issue.

PS: It's a little bit rude to say "you *must* have missed" but I understand
that it wasn't your intention.


Re: [PHP] When is "z" != "z" ?

2006-06-06 Thread Martin Alterisio

2006/6/6, Rasmus Lerdorf <[EMAIL PROTECTED]>:


Martin Alterisio wrote:
> You're right about ++ operator not to be considered a math operator, my
> mistake. What I should have said is that the usual connotation and
expected
> behaviour of ++ and the comparison operators is to give iteration
> capabilities to a certain data type, as used in a for statement. For
> that to
> happen certain constrains must be true for these operators, one of them
> being: any < ++any, which is not true for the way these operators behave
in
> php.
>
> I'm not saying "It's wrong let's change it right away!", I completely
agree
> that these rules can be bent on a not strongly typed language. The point
> I'm
> trying to make, the thing I want to understant without a trace of doubt,
> is:
> is it really worthy the functionality supplied with the string ++
operator
> as it is? I don't see its usefullness yet.

It has been in PHP from the very beginning.  So 10+ years.  In that time
it has been sparingly used, granted, but at the same time it really
hasn't gotten in the way and removing it would break a number of legacy
applications.



Well, that's enough reason to me, although a pain in the ass, backward
compatibility is an important issue. There will be plenty of opportunities
in future versions to revise this, for now my mind is at ease.

There were a lot more operators that worked on strings in the early

days.  '*' would do a cross-product, for example, treating the two
string operands as vectors and returning a vector orthogonal to both of
these.  But I got tired of trying to explain to people what a cross
product was and how strings mapped to vectors in Euclidean space and
removed that.  You could also at one point do "abc"-"b" to get "ac".

-Rasmus



That's quite an anecdote, why isn't it somewhere in the php website or
manual? It's nice to know the humans behind the soft ^_^

That kind of operation might have been useful with arrays, as some other
operations to work with them as if they were sets (inclusion, union,
difference, etc). Yes, we have functions for that but apply a few of them
inside an if statement and I start to have LISP nightmares with all those
parenthesis.


Re: [PHP] When is "z" != "z" ?

2006-06-06 Thread Martin Alterisio

2006/6/6, Barry <[EMAIL PROTECTED]>:


Martin Alterisio schrieb:

> is it really worthy the functionality supplied with the string ++
operator
> as it is? I don't see its usefullness yet.

guess you want to order something by "name" not by number which might be
false in some cases (1,10,2,20,21 ... and so on).

There it might be useful.

Well i don think it is wrong behavior in that way.

because having looping from a till z you wil get "aa" after z  so that
means aa is "higher" as z internally.

but looping till "aa" dont brings out a-z like you get a-y when you loop
till z (remember: for $i = a; $i <= z; $i++ gives the chars a-yz z right
followed by "aa")

Well if you implement something like that into a programming language it
should at least have some kind of logic behavior. Don't you think?



That's okay, but not where my doubts are. I have not objections to the
comparison made alphabetically. What I doubt is the usefullness of
generating sequences with ++.


Re: [PHP] When is "z" != "z" ?

2006-06-06 Thread Martin Alterisio

2006/6/6, Robert Cummings <[EMAIL PROTECTED]>:


On Tue, 2006-06-06 at 00:01, Martin Alterisio wrote:
> > Because defining ++ and < and > in such a way as to make them "behave
like
> > numbers" would have made them not work for alphabetizing.  A string is
a
> > string, and comparison of strings is alphabetic (for some definition
of
> > alphabet).  It's more useful to deal with strings as strings than to
make
> > them quack like numbers.
> >
>
> Then, if it's not a math operation, why use a math operator for such
> functionality? In which way is the ++ operator that generates a string

I don't ever remember seeing ++ in math class. I do remember seeing it
in lots of computer classes and to that end it was "just an operator"
with whatever semantic meaning was applied to it for a given language. I
guess it's usually to increment an integer, but that's just "in
general". I mean if we want to get into "math" operators being used for
string purposes, then we should look at how many languages use the "+"
operator to concatenate two strings -- by your accounts they should
treat their operands as integers and do a rote addition.

> sequence, useful enough to justify the formal inconsistency between the
math
> operators? I still don't see the advantages of having the ++ recognize
the
> string as a sequence, and generate the next item in the sequence. I
believe
> those decisions should be left to the coder, because he knows what the
> string really represents and which kind of sequence is being used.

In C++ they do leave it to the coder, and well, we all know what a mess
it can be deciphering overloaded operators in C++ (or maybe we ALL
don't). At any rate, the PHP overlords made a choice, and IMHO the best
choice. For such a fringe issue I don't see what the argument is all
about. If you want the functionality you get in C by incrementing a
char, then use the chr() function on an integer.



You're right about ++ operator not to be considered a math operator, my
mistake. What I should have said is that the usual connotation and expected
behaviour of ++ and the comparison operators is to give iteration
capabilities to a certain data type, as used in a for statement. For that to
happen certain constrains must be true for these operators, one of them
being: any < ++any, which is not true for the way these operators behave in
php.

I'm not saying "It's wrong let's change it right away!", I completely agree
that these rules can be bent on a not strongly typed language. The point I'm
trying to make, the thing I want to understant without a trace of doubt, is:
is it really worthy the functionality supplied with the string ++ operator
as it is? I don't see its usefullness yet.


Re: [PHP] When is "z" != "z" ?

2006-06-05 Thread Martin Alterisio

2006/6/6, Larry Garfield <[EMAIL PROTECTED]>:


On Monday 05 June 2006 21:12, Martin Alterisio wrote:

> > As for the increment, it actually would never have occurred to me to
++ a
> > string before this thread, honestly. :-)  However, what it appears to
be
> > doing (and I'm sure Rasmus will correct me if I'm wrong) is using a
> > "string
> > base" instead of a numeric base.  Thus a++ = b, b++=c, etc.  z++
"rolls
> > over"
> > to the next "digit" (which because it's a string goes to the right
rather
> > than the left), and resets.  So just as 9++ rolls over to 10, z rolls
> > over to
> > aa.
> >
> > Does that make more sense?
>
> You misunderstood me, I completely understand how the operators
function,
> but you're saying it makes sense the way their functionality is
assigned,
> what I want to know is the reasons you have that support those
> affirmations. I completely understand that string comparison is done
> alphabetically, but how does having the functionality for the ++
operator
> create a sequence that are inconsistent with the comparison operator,
makes
> sense?

Because defining ++ and < and > in such a way as to make them "behave like
numbers" would have made them not work for alphabetizing.  A string is a
string, and comparison of strings is alphabetic (for some definition of
alphabet).  It's more useful to deal with strings as strings than to make
them quack like numbers.



Then, if it's not a math operation, why use a math operator for such
functionality? In which way is the ++ operator that generates a string
sequence, useful enough to justify the formal inconsistency between the math
operators? I still don't see the advantages of having the ++ recognize the
string as a sequence, and generate the next item in the sequence. I believe
those decisions should be left to the coder, because he knows what the
string really represents and which kind of sequence is being used.


Re: [PHP] When is "z" != "z" ?

2006-06-05 Thread Martin Alterisio

2006/6/5, Larry Garfield <[EMAIL PROTECTED]>:


On Monday 05 June 2006 14:56, Martin Alterisio wrote:
> 2006/6/5, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
> > This is just one of those cases where the designers had to make a
> > judgement call on how things were going to operate.  It makes sense if
> > you look at the two things separately (incrementing vs string
'greatness'
> > evaluation) and makes sense that how they chose to implement the
> > functions are two valid choices among many ways that it could have
been
> > handled.
>
> How does it make sense? I don't understand your argument, can you
explain
> it a little bit more?

See Robert Cummings' post.  < and > are being interpreted in this case for
alphabetical order.  Read "<" as "alphabetically before", and <=
as "alphabetically before or string-equal to".

Is a alphabetically before or string-equal to z?  TRUE.
Is b alphabetically before or string-equal to z?  TRUE.
...
Is z alphabetically before or string-equal to z?  TRUE. (string-equal)
Is aa alphabetically before or string-equal to z?  TRUE. (a < z
alphabetically, the second character is never checked).
Is ab alphabetically before or string-equal to z?  TRUE.
...
Is yz alphabetically before or string-equal to z?  TRUE.
Is za alphabetically before or string-equal to z?  FALSE.  (a
alphabetically
after NULL character.  Bob is alphabetically before Bobby for the same
reason.)

See how the comparison works?  It's a purely alphabetic comparison.

As for the increment, it actually would never have occurred to me to ++ a
string before this thread, honestly. :-)  However, what it appears to be
doing (and I'm sure Rasmus will correct me if I'm wrong) is using a
"string
base" instead of a numeric base.  Thus a++ = b, b++=c, etc.  z++ "rolls
over"
to the next "digit" (which because it's a string goes to the right rather
than the left), and resets.  So just as 9++ rolls over to 10, z rolls over
to
aa.

Does that make more sense?



You misunderstood me, I completely understand how the operators function,
but you're saying it makes sense the way their functionality is assigned,
what I want to know is the reasons you have that support those affirmations.
I completely understand that string comparison is done alphabetically, but
how does having the functionality for the ++ operator create a sequence that
are inconsistent with the comparison operator, makes sense?


Re: [PHP] When is "z" != "z" ?

2006-06-05 Thread Martin Alterisio

2006/6/5, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:


This is just one of those cases where the designers had to make a
judgement call on how things were going to operate.  It makes sense if you
look at the two things separately (incrementing vs string 'greatness'
evaluation) and makes sense that how they chose to implement the functions
are two valid choices among many ways that it could have been handled.



How does it make sense? I don't understand your argument, can you explain it
a little bit more?


From a developers point of view it becomes "it is what it is".  Now
understanding the nature of the beast we must accept that this is just how
PHP works.  It's not wrong, it's just strange when it comes to z++ combined
with a for loop.  Probably an unforeseen disconnect when designing PHP but
the most important thing is understanding HOW it works (more so than 'why'
it was designed that way) and coding accordingly.



I agree, this is what we have and what we asked for, we wanted to use
strings on a math context and these things are bound to happen. But still
saying that something is right/wrong/not right/not wrong in CS is a bold
statement. On a certain context something may seem right but when the
context changes it turns out to be wrong, for example suppose we have a
programming language that handles strings the way PHP does, and it
implements templates or generics (the term you prefer the most). The
template/generic should have to be aware of strings when using math
operators, because they don't behave the way a math literal would.

There are many other ways to accomplish an A-Z sequence so as long as what's

been discussed is understood as "just how PHP is", and that it's logical for
certain purposes, then we can choose one of the other choices for solving
the problem.



I don't think it's only about us as developers using PHP, but us as
community giving back something to the community. This might be a small
issue but what would be the whole point of being an open-source community if
we can't at least discuss about it? "It just the way things are" is not an
argument, it's an excuse.

-TG





Re: [PHP] When is "z" != "z" ?

2006-06-04 Thread Martin Alterisio

2006/6/4, Rasmus Lerdorf <[EMAIL PROTECTED]>:


Martin Alterisio wrote:

> Still:
> anything < ++anything
> should be true, or at least that's what they taught me on abstract data
> types design, and I think they're right (at least this time)

In loosely typed languages that is not always true.  Operators have to
guess at the type and try to do what the user expects.  There will
always be edge cases.  Being able to increment strings is pretty handy
when you need to create sequences for unique file and directory names.

For example, this also works:

$filename = "file1";
$filename++;
echo $filename;

You would get "file2" from this.  Think about the amount of code you
would need to write in C to make that work?

Then change $filename to "fileA" and increment it.  And you get "fileB".
  When we get to "fileZ" we don't want to go off into unprintable
character land, we want to try to stick with the pattern.

-Rasmus



I still don't see why this functionality should be a native operator of the
language.
It doesn't seem natural that ++ operator "understands" that the string could
be an enumeration of some kind. I believe that such things should be left to
the coder who knows what the string is really representing, not to the
language.


Re: [PHP] When is "z" != "z" ?

2006-06-04 Thread Martin Alterisio

2006/6/4, Rasmus Lerdorf <[EMAIL PROTECTED]>:


Martin Alterisio wrote:
> 2006/6/4, Rasmus Lerdorf <[EMAIL PROTECTED]>:
>>
>> tedd wrote:
>> > Hi gang:
>> >
>> > Here's your opportunity to pound me again for not knowing the basics
of
>> php.
>> >
>> > I vaguely remember something like this being discussed a while back,
>> but
>> can't find the reference.
>> >
>> > In any event, if one uses --
>> >
>> > for ($i="a"; $i<"z"; $i++)
>> >   {
>> >   echo($i);
>> >}
>> >
>> > -- it stops at "y"
>> >
>> > But, if you use --
>> >
>> > for ($i="a"; $i<="z"; $i++)
>> >   {
>> >   echo($i);
>> >}
>> >
>> > -- it prints considerably more characters after "z" than what one
would
>> normally expect -- why is that?
>> >
>> > Just stopping at "z" would seem to make more sense, wouldn't it?
After
>> all, when $i = "z" in the first expression, then wouldn't $i be equal
>> to "z"
>> in the second expression and thus halt the operation?
>> >
>> > What am I missing here?
>>
>> It's a bit of a quirk.  "z"++ is "aa" and "aa" < "z".  I would guess
>> this would loop until until just before "za" which would be "yz".
>
>
> What?
> "z"++ < "z" returns true? =S
> Is there a reason for this? Why aren't they handled like C chars?

Because PHP is not C.  If you want them handled by their char codes,
then do so with chr() calls.



That's cool, but you missed my point, I was just wondering why the ++
operator for string was handled that way. I used the C comparison becuase
it's more usual for coders to think as chars in terms of their position in
the ASCII table, allowing loops such as the mentioned above. I'm not trying
to start another witch hunt, there are enough rantings around for that
purpose.


It's a bit like looping through the hexadecimal characters.  You would
>> have the same effect.  However instead of being base-16 with 0-9-a-f
you
>> have base-26 using a-z.
>
>
> 0xF++  would be 0x10 which is greater than 0xF (0xF < 0x10). It's not
the
> same.

Sure it is.  If you treat 0x10 as a string the same way he is treating
these as strings, then 0x10 is going to be smaller than 0xF.

The fact is that there is just no right answer for what "z"++ should do.

-Rasmus



Still:
anything < ++anything
should be true, or at least that's what they taught me on abstract data
types design, and I think they're right (at least this time)


Re: [PHP] When is "z" != "z" ?

2006-06-04 Thread Martin Alterisio

2006/6/4, Rasmus Lerdorf <[EMAIL PROTECTED]>:


tedd wrote:
> Hi gang:
>
> Here's your opportunity to pound me again for not knowing the basics of
php.
>
> I vaguely remember something like this being discussed a while back, but
can't find the reference.
>
> In any event, if one uses --
>
> for ($i="a"; $i<"z"; $i++)
>   {
>   echo($i);
>}
>
> -- it stops at "y"
>
> But, if you use --
>
> for ($i="a"; $i<="z"; $i++)
>   {
>   echo($i);
>}
>
> -- it prints considerably more characters after "z" than what one would
normally expect -- why is that?
>
> Just stopping at "z" would seem to make more sense, wouldn't it? After
all, when $i = "z" in the first expression, then wouldn't $i be equal to "z"
in the second expression and thus halt the operation?
>
> What am I missing here?

It's a bit of a quirk.  "z"++ is "aa" and "aa" < "z".  I would guess
this would loop until until just before "za" which would be "yz".



What?
"z"++ < "z" returns true? =S
Is there a reason for this? Why aren't they handled like C chars?

It's a bit like looping through the hexadecimal characters.  You would

have the same effect.  However instead of being base-16 with 0-9-a-f you
have base-26 using a-z.



0xF++  would be 0x10 which is greater than 0xF (0xF < 0x10). It's not the
same.

-Rasmus


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




Re: [PHP] How do I make a HTML tree for a set of nodes?

2006-06-04 Thread Martin Alterisio

2006/6/4, Niels <[EMAIL PROTECTED]>:


Hi!

On Sunday 04 June 2006 18:13, Martin Alterisio wrote:
[snip]

> I had a similar problem that, although it was with a binary tree, it can
> be used with your tree. PHP doesn't like too much the use of recursion,
> but this time recursion is the way to go (if you want to keep the code
> maintainable). Hopefully the tree will not span deep enough to cause any
> problems... (hopefully).
>
> The function will receive a node and return a table representation of
the
> branch started by this tree, if you point this function to the root node
> you'll have your table. In each cell it will have to indicate whether it
> is empty, it has a node or a line connecting neighbor cells. One
important
> thing to define here is the way the function will organize the nodes in
> the table, in my function the root node was at the top in the center.
>
> First, the trivial case: if the node doesn't have children return a
table
> with one cell, the node itself.
> Then, the recursive case: if the node have children, call the function
> with those nodes and store the tables returned. According to the
> representation I used, it calculated the combined width of those tables,
> created a new table where the first row contained the parent node
> centered, the second line an horizontal line from the column where the
> first children would be to the column where the last children would be.
> Then it build the rest of the table pasting together, horizontally, the
> tables of the children. Voila! a nice table representation of the tree.

This sounds fine -- recursion is obviously the way to go. Where can I see
your function?

I tried several different solutions over the last couple of hours, and
I've
settled on only using indentation (like a nested  list), not a
fancy graph with antialised branches. It's the simplest possible recursion
but I like the results, even if it's a bit harder to grasp without
connections clearly marked.


function tree($nodes, $start, $indent=-30) {
$indent+=30;
global $tree;
foreach ($nodes as $nodeID => $node) {
if ($node['parent']!=$start) {continue;}
$tree.="{$node['name']}";
tree($nodes, $nodeID, $indent);
}
return $tree;
}



Thanks!

//Niels

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Sorry, I can't show you the code. Anyway you don't seem to need it. One
recommendation, don't rely on global vars, look at this:

function tree($nodes, $start, $indent=-30) {
   $indent+=30;
   $tree = "";
   foreach ($nodes as $nodeID => $node) {
   if ($node['parent']!=$start) {continue;}
   $tree .= "{$node['name']}";
   $tree .= tree($nodes, $nodeID, $indent);
   }
   return $tree;
}


Re: [PHP] How do I make a HTML tree for a set of nodes?

2006-06-04 Thread Martin Alterisio

2006/6/4, Niels <[EMAIL PROTECTED]>:


Hi,


I have a set of nodes. Each node has a parent and so the set can be
thought
of as a tree. I want to show that tree somehow on a webpage, served by
PHP.
I cannot use Dot/Graphwiz for various reasons. What I'm looking for is an
output of DIVs or tablecells, showing the nodes and their connections.
It's
not a trivial task, IMO, but doable. Possibly somebody has already made
something similiar, but I can't find anything on Google. Can anybody point
me to helpful information?

Thanks,
Niels

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



I had a similar problem that, although it was with a binary tree, it can be
used with your tree. PHP doesn't like too much the use of recursion, but
this time recursion is the way to go (if you want to keep the code
maintainable). Hopefully the tree will not span deep enough to cause any
problems... (hopefully).

The function will receive a node and return a table representation of the
branch started by this tree, if you point this function to the root node
you'll have your table. In each cell it will have to indicate whether it is
empty, it has a node or a line connecting neighbor cells. One important
thing to define here is the way the function will organize the nodes in the
table, in my function the root node was at the top in the center.

First, the trivial case: if the node doesn't have children return a table
with one cell, the node itself.
Then, the recursive case: if the node have children, call the function with
those nodes and store the tables returned. According to the representation I
used, it calculated the combined width of those tables, created a new table
where the first row contained the parent node centered, the second line an
horizontal line from the column where the first children would be to the
column where the last children would be. Then it build the rest of the table
pasting together, horizontally, the tables of the children. Voila! a nice
table representation of the tree.


Re: [PHP] Help with enter key in Forms

2006-06-02 Thread Martin Alterisio

2006/6/2, George Babichev <[EMAIL PROTECTED]>:


Awesome, thank you so much! It works!

On 6/1/06, Chris <[EMAIL PROTECTED]> wrote:
>
> George Babichev wrote:
> > Ok, I sent it to everyone and you. Now can you answer my question
> please?
> > I type in
> > 1
> >
> >
> >
> > 2
> > into my form in the program that i made, then when I view it, it shows
> > 1 2
> > BUT if I check it in PHP My Admin it displays
> > 1
> >
> >
> >
> > 2
>
> The answer is to change this:
>
> 
> to this:
>
> 
>
> like I said before...
>
> --
> Postgresql & php tutorials
> http://www.designmagick.com/
>



Now that your problem is solved it would be a nice idea to study a little
bit more about HTML and PHP so that you can find the explanation and
solution for this and other problems on your own. Please read the manual,
specially when someone is kind enough to point you the exact function to
look for.

PS: Have you understood what went wrong in your script? Have you understood
what is the purpose of nl2br? If not, the kindness of those who answered you
will have been in vain.


Re: [PHP] Using 'header' as redirect

2006-05-30 Thread Martin Alterisio

2006/5/30, Philip Thompson <[EMAIL PROTECTED]>:






Are you checking what the user is sending inside $_GET['page']? If not, your
system is vulnerable to a remote file injection.


Re: [PHP] Including Functions; one file or many?

2006-05-27 Thread Martin Alterisio

2006/5/27, Jochem Maas <[EMAIL PROTECTED]>:


2. any include file that does contain code that runs on inclusion contains
something
like the following as the first line of code:

if (!defined('MY_APP_IS_SETUP')) die('try
http://'.$SERVER['SERVER_NAME'].'/');



An enhancement to this strategy could be using an error header to prevent
exposing the internal structure of your site:

if (!defined('MY_APP_IS_SETUP')) {
header("Status: 404 Not Found");
die;
}


Re: [PHP] Re: Can php convert doc to HTML?

2006-05-23 Thread Martin Alterisio

2006/5/23, Jochem Maas <[EMAIL PROTECTED]>:


my 2cents 

Martin Alterisio wrote:
> 2006/5/23, Dotan Cohen <[EMAIL PROTECTED]>:
>
>>
>> On 5/23/06, Martin Alterisio <[EMAIL PROTECTED]> wrote:
>> >
>> > If that's the case, why don't you just use the "export as web page"
or
>> "save
>> > as web page" tools of MS Word (if you don't have it anymore you can
as
>> > someone who still has it, or I think OpenOffice also has a similar
>> tool).
>> >
>>
>> Because there are 200 of them.
>>
>> Dotan Cohen
>> http://what-is-what.com
>> 323
>>
>
>
> Open file, choose file, save as web page, close file ~ 2 minutes
> 200 files * 2 minutes = 400 minutes ~ 7 hours
> How much hours have you wasted looking for a php script?

even if it takes him 14 hours to find a script and get it working
he will have:

a, learnt quite abit about php'ing/html/etc
b, have the basis for a tool that can convert any future .doc
files that he finds/get thrown at him.

Martin the suggestion you give sucks because it doesn't empower,
it leaves Dotan with a sore wrist and no gain in knowledge...

maybe it's  good advice for 'noobs' on an Office mailing
but this is a lsit about programming (sure it's php and plenty of IT
related people consider us phpers to be the pretty much the lowest form
of programmer - well not as low as VBscripters ;-) - anyone reading,
posting
here, I would hope, aspires to a little more than PHB's secretary with
regards to their IT skills.



You're completely right about that. Maybe living too much at the edge of the
deadline has turned me into boring freak (most probably). I have to take
this way of thinking out my mind.



> Anyway, I understand... it's a pain in the ass. Whay you're doing wrong
is:
> you have turned your solution into a problem and forgot what the real
> problem was.

this assumes there is a 'problem' - maybe Dotan is driven more or less
by a desire to see if he can do it rather than being up against some
deadline
or having his boss breathing down his neck waiting for a result?



I disagree. There is always a problem, the kind of problem you're referring
to is "I'm lacking this knowledge, or I want to know how to do X", in his
case X would be "converting word docs to html with a php script".

My first impression was that this was his problem, but deducing from what he
explained after, I'm certain this isn't the problem he wants to solve, but
rather a solution he came up but is unable to put into practice.

I think this time PHP is not the solution. A shell script interacting with a
third party tool, or a C program interacting with a third party library will
be a much more appropiate solution.


Re: [PHP] Re: Can php convert doc to HTML?

2006-05-23 Thread Martin Alterisio

2006/5/23, Dotan Cohen <[EMAIL PROTECTED]>:


On 5/23/06, Martin Alterisio <[EMAIL PROTECTED]> wrote:
>
> If that's the case, why don't you just use the "export as web page" or
"save
> as web page" tools of MS Word (if you don't have it anymore you can as
> someone who still has it, or I think OpenOffice also has a similar
tool).
>

Because there are 200 of them.

Dotan Cohen
http://what-is-what.com
323




Open file, choose file, save as web page, close file ~ 2 minutes
200 files * 2 minutes = 400 minutes ~ 7 hours
How much hours have you wasted looking for a php script?

Anyway, I understand... it's a pain in the ass. Whay you're doing wrong is:
you have turned your solution into a problem and forgot what the real
problem was.

Why don't look for another solution:
http://www.google.com/search?q=batch+convert+word+to+html
But they'll probably ask money for it, so why don't just:
http://www.google.com/search?q=batch+convert+word+to+html+free


Re: [PHP] Re: Can php convert doc to HTML?

2006-05-23 Thread Martin Alterisio

2006/5/23, Dotan Cohen <[EMAIL PROTECTED]>:


On 5/23/06, tedd <[EMAIL PROTECTED]> wrote:
> At 7:09 PM +0300 5/23/06, Dotan Cohen wrote:
> >This may be far-fetched, but can php convert a doc file to HTML? I
> >vaguely remember a thread that discussed converting pdf's, but I
> >cannot find reference to either that or to doc in the manual. Any
> >input would be appreciated.
> >
> >If php cannot do this, then could someone recommend a tool that runs
> >on linux that can do the conversion in batch? I have ~200 files to
> >convert.
> >
> >Thanks.
> >
> >Dotan Cohen
>
> Dotan:
>
> What kind of documents and how to do want to present them?
>
> PHP can generate html code and place any text file within in it --
> it's simple a matter of arranging things the way you want it to look.
> For example, you might want to review:
>
> http://www.weberdev.com/get_example-1233.html
>
> In fact, you can do that without php by using a shtml and includes.
>
> But, more specifically, I need to know more about what documents you
> have and you what you want to do with them.
>
> tedd

Thanks for the example, Tedd. That script would work if I already had
the files in HTML format.

I have about two hundred .doc files that I have archived over the
years. Now that I'm rid of windows I would still like to use them. I
figure that the easiest way to still view the documents, and make them
available for others in my faculty, would be to publish them on
dotancohen.com . However, I'd need to convert them from .doc format to
HTML before I can put them on the web.

I know that I can just drag it all over to a winbox at the university
and convert them one-by-one in Word, but I'd rather not do that to 200
individual files!

Dotan Cohen
http://gmail-com.com
56



If that's the case, why don't you just use the "export as web page" or "save
as web page" tools of MS Word (if you don't have it anymore you can as
someone who still has it, or I think OpenOffice also has a similar tool).


Re: [PHP] PHP Notice: Undefined index

2006-05-19 Thread Martin Alterisio

2006/5/19, John Taylor-Johnston <[EMAIL PROTECTED]

:

Any idea why this bit of code

if("yes" == $_POST['submitter'])
{
mysql_select_db($db,$myconnection);

$sql = "INSERT INTO `$db`.`$table`
(name,email,comments,entrydate)
values ('$name','$email','$comments','$entrydate')";
mysql_query($sql) or die(print mysql_error());
}

is provoking this message in my Apache error log?

[Fri May 19 19:05:10 2006] [error] PHP Notice: Undefined index:
submitter in
/home/jtjohnston/domains/jtjohnston.ca/public_html/comments.php on line 29



John

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Try using:
if(isset($_POST['submitter']) && "yes" == $_POST['submitter'])


Re: [PHP] Converting characters

2006-05-17 Thread Martin Alterisio

2006/5/17, Jonas Rosling <[EMAIL PROTECTED]>:


Hi,
the PHP newbie is here again asking questions.
Is there anyway in PHP to convert none international characters so the are
displayed correct?
In my case I have lots of data in the database with å,ä and ö.

Thanks // Jonas

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




If your db uses a character encode that doesn't support all the characters
in the character set of the string you want to store, this characters will
be lost when converting from one set to another, and there will be no way to
convert them back. The proper solution is to set the correct character set
in your db.


Re: [PHP] Handling Large Check Box Data

2006-05-17 Thread Martin Alterisio

2006/5/17, Rahul S. Johari <[EMAIL PROTECTED]>:


Ave,

I¹m a little confused as to what¹s the best way to handle this.
I have a form which, apart from lots of other fields, has a set of 25 ­ 30
Check Boxes, each of which asks the user for some kind of information
which
the user can check or leave unchecked.
The information each Check Box collects will also appear in the ³Listing²
for users to view once the user has completed & submitted the form.
Furthermore, there is an Advanced Search also available to users which
will
also provide the same 25 - 30 check boxes which define the search
criteria.
I¹m not sure what¹s the best, most efficient way to do this.

The tedious way to do this is to make 30 fields in the mySQL database, and

if the check box is checked, the data goes into the corresponding field...
And similarly listing the data from the field if field is non-empty
And
similarly including each field in the Search options.

I want suggestions for a better/faster way to do this. I did think about
creating a single field and storing the data from each Œchecked¹ check box
as comma separated values in the single field. I¹m not sure how to do that

and if that¹s the best way But even if I can, I¹m not sure how to get
the data to display separately out of that field in the Listings view and
more importantly how to include that data in the Search options.

Any help would be appreciated.

Thanks,

Rahul S. Johari
Coordinator, Internet & Administration
Informed Marketing Services Inc.
500 Federal Street, Suite 201
Troy NY 12180

Tel: (518) 687-6700 x154
Fax: (518) 687-6799
Email: [EMAIL PROTECTED]
http://www.informed-sources.com





You should consider using MySQL special column type SET:

http://dev.mysql.com/doc/refman/5.1/en/set.html

Or encoding each checkbox status as a binary bit in an integer (which is
what MySQL does when using a SET column).


  1   2   >