Page 1 of 1

Tips for PHP code reutilization?

Posted: Wed May 22, 2024 9:43 am
by Giu
Hi all,

As my demo project start growing, I have to start thinking in reuse the same code I need in several different places. In standard PHP we move this code to libraries/classes and "include" them.

I guess here we have to use nuProcedure and/or nuRunProcedure.
I see nuProcedure returns the code as string to eval it, and nuRunProcedure executes directly this procedure.

Would like to know the "nuStandard" way to reuse code and "send params/receive data" from this code inside procs (returns? hash cookies?). There are ways to put several functions and reuse from one procedure? Main advantages/disavantadges between nuProc and nuRunProc? It's better to use a procedure for each function? What suggestions are about all of this?

Thanks.

Re: Tips for PHP code reutilization?

Posted: Wed May 22, 2024 9:59 am
by kev1n
Hi,

I have a set of PHP functions that I use across multiple forms, which are stored in an external PHP file.
To organise these, you can create e.g. a ‘libs’ folder in the nuBuilder root directory and place your PHP file(s) in this folder.

In nuconfig.php, search for the setting "$nuConfigIncludePHP" and include them like:

Code: Select all

$nuConfigIncludePHP	 = ['../libs/mylib1.php','../libs/mylib1.php'];
Example of external php file: mylib1.php:

Code: Select all

<?php

function myfunction($param) {
	// do something here
}

Re: Tips for PHP code reutilization?

Posted: Wed May 22, 2024 11:08 am
by Giu
But Hash cookies can be used there?

Re: Tips for PHP code reutilization?

Posted: Wed May 22, 2024 11:19 am
by kev1n
You can pass them as parameters to the function.

Re: Tips for PHP code reutilization?

Posted: Wed May 22, 2024 1:44 pm
by Giu
Oh, of course, you are right.

nuRunQuery can be run there in that functions too I guess? or what include we must do?

Thanks.

Re: Tips for PHP code reutilization?

Posted: Wed May 22, 2024 2:19 pm
by kev1n
Yes, nuRunQuery() can be used directly, there's no need to include the nu-core files again.