NotionCommotion
Members-
Posts
2,446 -
Joined
-
Last visited
-
Days Won
10
Everything posted by NotionCommotion
-
Using namespace with autoloader
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Gotcha! You wrote $path = str_replace("\\", DIRECTORY_SEPARATOR, $classname);, but I originally read $path = str_replace("/", DIRECTORY_SEPARATOR, $classname);which doesn't do much... -
Using namespace with autoloader
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Thanks again Requinix, I had previously tried \PDO but evidently did not do so on the script which was causing the error. I take it I should use it everywhere such as \PDOException, right? Also, even if I am not using namespace, I should do so, right? Don't really see what the point of the below script is. What is it doing? -
How do I extract partial string from a full string?
NotionCommotion replied to imgrooot's topic in PHP Coding Help
Good -
How do I extract partial string from a full string?
NotionCommotion replied to imgrooot's topic in PHP Coding Help
Good job getting the second step working. Understand that it will be several hundred rows, but are you doing so to fix the table? Your database should have a table for the company and a table for the product, and the application should create the combined string. Your database should not directly be saving the combined string. -
Using namespace with autoloader
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Thanks requinex, Okay, that answers my question when to use use. What about how to use spl_autoload_register, and how to prevent PHP from thinking that class PDO should be in my namespace? -
Using namespace with autoloader
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Why does PHP think that PDO should be in the MyNameSpace namespace? How do I prevent it from doing so? <?php namespace MyNameSpace; class MyParentClass { public function xyx() { // ... $bla=$stmt->fetch(PDO::FETCH_OBJ); } } -
How do I extract partial string from a full string?
NotionCommotion replied to imgrooot's topic in PHP Coding Help
Are you doing this just once to fix a badly designed table? If not, you shouldn't be doing this. To do the next step, just do it the same way. Figure out where your deliminator position is using strpos(), and use substr() to return the correct string. -
How do I extract partial string from a full string?
NotionCommotion replied to imgrooot's topic in PHP Coding Help
Maybe? <?php function getIt($var) { $pos = strpos($var, ' - '); echo(substr($var, $pos+3)."\n"); } $variable_1 = 'Lulu-free - Swimsuit swimwear red'; $variable_2 = 'Pap & Jones - Bard Mini Dress'; getIt($variable_1); getIt($variable_2); -
How do I extract partial string from a full string?
NotionCommotion replied to imgrooot's topic in PHP Coding Help
Is it fair to say that " - " will always separate the two strings? Will a hyphen ever be in the second string part? -
I haven't really been using namespace, and after reading PSR, I thought I should. Some errors, however.... It is my understanding that the classes should be like the following two. Correct? <?php namespace MyNameSpace; class MyParentClass { //.... } namespace MyNameSpace; class MyChildClass extends MyParentClass { //.... } To create an object, I would do?? When is use used? $pdo=new PDO(/*...*/); $myChild=new \MyNamespace\MyChildClass(); How should my autoloader be? spl_autoload_register(function ($classname) { $parts = explode('\\', $classname); require "../classes/".end($parts).'.php'; //require ("../classes/" . $classname . ".php"); });
-
Thank you Ignace and Jacques1. PSR-1 is a good reference. My bad, an array is just a variable. Regarding array elements: $myArr['myElement'], what should "myElement" be? Also, if my class name is MyClass, should the filename be MyClass.php or myclass.php?
-
Also, what about filenames for classes and normal files?
-
I am currently inconsistent on my naming convention, and would like to better standardize. If starting from scratch, what would you recommend for the following for PHP? I included what I think are the best optons below, but if it should be something totally different, please advise. While outside of the scope of this forum, recommendations for JavaScript would also be appreciated. Thank you Classes: PascalCase Name Spaces: PascalCase or camelCase? Methods: camelCase or lower_case? Properties: camelCase or lower_case? Functions: camelCase or lower_case? Variables: camelCase or lower_case? Arrays: camelCase or lower_case? Array Elements: camelCase or lower_case? Anything I am missing? Also, for each, should they be plural or singular?
-
Regarding "main" class, yea, it does seem that way. Slim acts as the controller, "documents" is a model with a bit of logic, and "main" adds some methods used by "documents" and other similar models. They are different tables. I will have a super-type table "documents" with 1-to-1 relationship to sub-type tables "drawings" and "specifications". Deleting might be the same, but other tasks such as editing are different. The constructor was being used for authentication. I've since changed, and will use what I think is the "slim way" as following. $app->add(function ($request, $response, $next) { if(empty($_SERVER['HTTP_X_KEY'])){ http_response_code(422); exit(json_encode(["status"=>"error","code"=>3,"message"=>"Missing key."])); } else { $stmt=$this->db->prepare('SELECT id, timestamp FROM accounts WHERE key=?'); $stmt->execute([$_SERVER['HTTP_X_KEY']]); if(!$this->account=$stmt->fetch(PDO::FETCH_OBJ)){ http_response_code(422); exit(json_encode(["status"=>"error","code"=>3,"message"=>"Invalid key."])); } } $response = $next($request, $response); return $response; });
-
I have the following application where a DELETE HTTP request method to url http://example.com/documents/123 will delete document 123 of the account corresponding to the key sent in $_SERVER['HTTP_X_KEY']. //index.php use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; require '../vendor/autoload.php'; spl_autoload_register(function ($classname) { require ("../classes/" . $classname . ".php"); }); $config=parse_ini_file('../../config.ini',true); $config=[ 'db_sql'=>$config['mysql'] ]; $app = new \Slim\App(["settings" => $config]); $container = $app->getContainer(); $container['logger'] = function($config) { $logger = new \Monolog\Logger('my_logger'); $file_handler = new \Monolog\Handler\StreamHandler("../logs/app.log"); $logger->pushHandler($file_handler); return $logger; }; $container['db'] = function ($config) { try { $db = $config['settings']['db_sql']; return new PDO("mysql:host={$db['host']};dbname={$db['dbname']};charset={$db['charset']}",$db['username'],$db['password'],array(PDO::ATTR_EMULATE_PREPARES=>false,PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>true,PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC)); } catch(PDOException $e){ header("HTTP/1.1 503 Service Unavailable. MySQL database is down."); exit(json_encode(["status"=>"error","code"=>2,"message"=>"Unable to communicate with database."])); } }; $app->delete('/documents/{documents_id}', function (Request $request, Response $response) { $documents=new documents(['logger'=>$container['logger'],'db'=>$container['db']]); return $response->withJson($documents->delete($request->getAttribute('documents_id'),$request->getParsedBody())); }); $app->run(); class main { protected $db, $logger, $account; public function __construct($settings) { foreach($settings as $key=>$value) { $this->$key=$value; } if(empty($_SERVER['HTTP_X_KEY'])){ http_response_code(422); exit(json_encode(["status"=>"error","code"=>3,"message"=>"Missing key."])); } else { $stmt=$this->db->prepare('SELECT id, timestamp FROM accounts WHERE key=?'); $stmt->execute([$_SERVER['HTTP_X_KEY']]); if(!$this->account=$stmt->fetch(PDO::FETCH_OBJ)){ http_response_code(422); exit(json_encode(["status"=>"error","code"=>3,"message"=>"Invalid key."])); } } } } class documents extends main { public function delete($documents_id,$params) { /* Delete document based on $documents_id and $this->account->id Set headers as appropriate return JSON */ } } I wish to change this, and instead of having just class "documents", have several classes based on the type of the document (i.e. drawings, specifications ,etc), and have those classes extend the parent documents class. I have a table "documents" which contains: id (PK) accounts_id documents_id (this is the id sent from the client, and is unique for a given accounts_id) type (i.e. drawings, specifications ,etc. This is what determines the desired class) My first thought was to within index.php query the documents table to determine the type of document based on the received documents_id and the accounts_id, but I don't know the accounts_id until the classes constructor is executed. I am thinking maybe I should be using middleware for authentication and determining the accounts_id, but am not really sure. Any recommendations?
-
Creating an object without knowing the class name
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Didn't know if I could/should create an object $animal=new animal(2) use the constructor to query the DB and return the object based on the appropriate class. Sounds a little recursive, so I expect not, but thought there might be something similar which was acceptable. -
I have classes "dogs", "cats", and "mice", and each extends class "animals". I have a table with primary integer key "id" (1, 2, 3) and unique column "animal_type" ("dogs", "cats", and "mice"). Given id of 2, how can I create a cats object without first querying the database to get the animal type?
-
Preventing Twig from escaping JSON
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Thanks Jacques, I will use an existing element. Probably not body, however, as an extended template will be used to generate the the body tag, menu, etc. Agree, or am I missing something? -
Preventing Twig from escaping JSON
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
<div id="types" data-types="{{ types|json_encode() }}"></div> Forgot I was using twig -
Preventing Twig from escaping JSON
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Maybe? <div id="myJSONdiv" data-json="<?php echo htmlentities(json_encode($jsonArray), ENT_QUOTES, 'UTF-8'); ?>"></div> -
Preventing Twig from escaping JSON
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Please give an example. Thanks -
Preventing Twig from escaping JSON
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Ah, I see. {% set _jsScript = [ 'var types='~types|json_encode()~';' ] %} {% macro listArray(list) %} {% for item in list %} {{ item|raw }} {% endfor %} {% endmacro %} {% if _jsScript|default %} <script type="text/javascript"> {{ forms.listArray(_jsScript) }} </script> {% endif %} -
types is an array or object. How do I prevent it from being escaped? Thanks {% set _jsScript = [ 'var types=$.parseJSON('~types|json_encode()|raw~');' ] %} {% macro listArray(list) %} {% for item in list %} {{ item }} {% endfor %} {% endmacro %} {% if _jsScript|default %} <script type="text/javascript"> {{ forms.listArray(_jsScript) }} </script> {% endif %}
-
True statement, and maybe I should change my approach. I do feel, however, objects are a little more readable and concise. Why, yes it does! I swore my array got changed to an object. Must have been some other error elsewhere.
-
This was my first approach,, however, I am using it to add to an object created by json_decode(), it it needs to be in the form I described. That is what I had done after my first approach, but data also gets changed to an object which not desired.