Basic

PHP Latest version: 8.4 (2024)

PHP Life cycle:

  • Tokenizing      : Interpreter read the code
  • Parsing         : Code read by the interpreter gets parsed and tested if the syntax rules    are passed.
  • Compilation     : Compiling the code
  • Interpretation  : Interpret and run the code

Dynamically Typed Language:

PHP is a dynamically typed language, where the variable types are checked at runtime and so the variables do not require type declaration. 

Code Execution in PHP:

In general, the execution of code is performed in 2 steps,

1. Compilation, in which, the source code is translated into machine code (binary instructions). During this time, the variable types are checked, syntax errors are checked, optimisation (code is improved for better performance)

2. Run time, in which, the compiled program is executed and performs its tasks. It can cause run time errors, logical errors, etc.

Since, PHP is an interpreted language, it behaves differently from the statically compiled languages, so the compilation time is often handled dynamically at runtime.

Compilation in php:

In php, instead of traditional compilation, the PHP interpreter parses the code and converts it into an intermediate format known as opcodes (operation codes). These opcodes are then executed by the Zend Engine (PHP’s execution engine). This process happens dynamically during execution and is not a separate compile-time phase like in languages such as C or Java.

PHP interpreter:

PHP code is not directly converted into machine code (binary instructions) that the computer’s processor can execute. Instead, it is executed by an intermediary software program called the PHP interpreter.

PHP Interpreter Internals:

Opcache: A caching mechanism that stores precompiled opcodes to speed up repeated script executions. Zend Engine: parsing, compiling, and execution of PHP scripts. Extensions: Extensions like mysqli, curl, etc. add extra functionality to the interpreter

Disadvantages:

  • Tightly coupled.
  • Weakly typed
  • Supports type juggling. Variable type is auto assigned.
  • Not for large applications because its not extremely modular
  • Not Intended to strictly follow the PCR rules and coding standards
  • Security concern, since it is open sourced, so all people can see the source code, if there are bugs in the source code, it can be used by people to explore the weakness of PHP

Statically typed vs Dynamically typed:

In dynamically typed languages, In dynamically typed languages, the variable types are checked at runtime, and so, the variables do not require explicit type declarations. 

e.g., Python, JavaScript, php, etc.

But in statically typed language, the variable types are checked during compilation time and so their variables should be declared before. The compiler uses this information to validate all data types during compilation. 

e.g., C, C++, Java, Go, etc.


5.6 vs 7:

  • performance improvement (optimized memory usage)
  • Handling fatal and catchable fatal errors have never been an easy task for PHP coders. The new Engine Exceptions will allow you to replace these kind of errors with exceptions. 

PDO:

It is a well-designed API. This is an acronym for “PHP data objects”. PDO is a lean, consistent way to access databases. Or we can say It provides lightweight interface for accessing databases. It provides prepared statements, and significant flexibility in how data is returned.

PDO Advantages:

  • This follow rules of Object oriented programming
  • Need not to worry about SQL injection
  • It auto validate the input data
  • The predefined set of functions perform the error handling and Throws catchable exceptions 
  • Provide helpful methods like lastInsertId, DeleltedRecordId etc

Single Line Answers:

  • Type Casting: The way, php assign types to the variables is called type casting.
  • Type juggling: When the type of variable is changed based on the assigned value, this is called type juggling.
  • Scope Variable: Scope is an object that is used for binding between the presentation layer (HTML view) and the business layer (JavaScript controller). Since this is an object, and so, it has its own properties and methods.
  • YODA conditions in php: Keep the constant side at left side.
  • Strict_types in PHP:
    • In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown.
    • The only exception to this rule is that an integer may be given to a function expecting a float. Function calls from within internal functions will not be affected by the strict_types declaration
    • Statement: declare(strict_types=1);
  • ORM: Object-relational mapping technique for converting data between incompatible type systems using object-oriented programming languages
  • Scaffolding: Processes of automatic generating the code for specific functionalities based on predefined templates or components.
  • Boilerplate: Boilerplate refers to standardized, reusable code, templates, or content that provides the foundational structure or setup for a project.

Object Oriented Concepts:

  • Class: Set of instructions
  • Object: Instances of class
  • Constructors: Functions on the class which are called automatically
  • Destructors: Functions which should be called after the complete lifecycle to release the memory
  • Static Variable: Class Variable, Does not depends on objects.
  • Ambiguity: A situation where the two parent classes have the same function.
  • Ambiguity Solution: Make them static and call statically (with the class name)
  • Function Overriding: When a parent method is replaced by the child method, it is called overriding.
  • Function Overriding purpose: Changing the behavior of parent class.
  • Function Overloading: When a function is responsible for performing multiple tasks, based on the number of arguments or type of argument, it is called function overloading.
  • Final:
    • Final Class: Which can not extend other classes.
    • Final Function: Which not not be overridden.
    • Final Variable: Which can be assigned only once.

About version stability:

  • stable
  • RC (Release Candidate): 
  • beta: completed but may have issues
  • alpha: not-completed and may have issues
  • dev: under development

Types of class:

  • Super/Parent/Base Class: which is extended by a subclass
  • Sub/Child class: which is extending
  • Final class: which can not extend other classes 
  • Abstract class: Which contains atleast one abstract method.

Types of Variables:

  • Local variable: Inside function
  • Global variable: Outside function, In general on top or in constructor. Its scope will be throughout the whole cycle.

Moving On:

  • Inheritance: Inheriting properties and methods of other class by extending it into the current class.
  • Encapsulation (Data Security):
    • Restricting direct access to the data
    • Achieved by Access modifiers (Public, Private, Protected)
  • Abstraction:
    • Hiding implementation details
    • Achieved by Abstract classes, Interfaces, or Abstract methods.
  • Abstract method: Method that is declared, but not implemented
Abstract ClassInterface
DefinitationClass, that can have both, abstract method (without implementation) and concrete methods (with implementation)Blueprint, that defines abstract methods to be implemented by a class
InheritanceA class can extend only one abstract classA class can implement multiple interfaces
PropertiesIt can have properties as well.Interface does not contain properties.
Implementation:abstract class Animal {
}

class Dog extends Animal {
}
interface Animal {
}

class Dog implements Animal {
}

Note: PHP does not support multiple Inheritance. But it can implement multiple interfaces.

  • Polymorphism: Same methods of multiple classes returns different response based on the type of object.

this:

  • It refers to the current object of a class.
  • It is called as pseudo-variable because, it is not the actual variable. It behaves like a variable to reffer to the current instance of the class.
  • the pseudo-variable $this is not available inside the method declared as static.

One liners:

  • Member Variable: Variables are defined inside a class, which are invisible to the outside world.
  • Member Function: Functions used to access the object data.
  • Data Modeling: Creating get set functions is called data modeling.
  • Garbage Collection: When a lot of unsaved variables, objects, arrays are collected in the memory, this is called Garbage collection.
  • Memory taken by class: It depends on the uses of the class. If the class is created efficiently, reusing the codes, following SOLID principles…memory consumption will be less.

SOLID Principles:

  1. Single Responsibility Principle
  2. Open closed principle: Open to extend but closed for modification
  3. Liskov Substitution Principle: Object of superclass should be replacable by the object of sub class without affecting program.
  4. Interface Segregation Principle: Create small interfaces. No need to implement everything that is declared in a single big interface.
  5. Dependency Inversion Principle: High-level modules should not depend on low-level modules. Both should depend on abstractions.

REST:

  • Representational State Transfer
  • REST are the web standards, which are used to exchange the data between systems. It provides a predefined set of rules and follows the http protocols to implement the communication chain like GET, POST, PUT and DELETE. 
  • Follows six constraints : Uniform Interface, Client-Server, Stateless, Cacheable, Layered System, Code on Demand.
  • XML, JSON, Plain-text

SOAP:

  • Simple Object Access Protocol, strict, XML

Error codes:

  • 200- OK
  • 201- Created
  • 304- Not Modified
  • 400- Bad Request (the request was invalid or missing required parameters)
  • 401- Unauthorized (the client needs to authenticate to access the resource)
  • 403- Forbidden (Web server don;t have rights to process request)
  • 404- Not Found
  • 422- Unprocessable Entity (Server is unable to process the contained instructions)
  • 500- Internal Server Error (an unexpected error occurred on the server)

REST vs SOAP:

  • SOAP is a standards-based Web services access protocol
  • REST provides a truly simple method of accessing Web services
  • SOAP relies on XML to provide messaging services. 
  • REST relies on a simple URL
  • Soap is good for large applications
  • Rest is good for small

nonce: 

  • A random number
  • Problem: Without a nonce, a malicious client (frontend user) could generate a request ONCE and replay it MANY times.
  • Solution: Nonces are used to make a request unique. So with a nonce, the replay attack is prevented based on the nonce. It makes the request unique.

API Caching:

REST API caching is the process of storing the responses of RESTful web service requests in a cache server, such as a reverse proxy, a content delivery network (CDN), or a cloud service. The cache server intercepts the incoming requests and returns the cached responses if they are valid and fresh, without contacting the origin server. This can reduce the network latency, the server load, and the bandwidth consumption.

Types of cloud services:

  • SAAS:
    • Definition: It means that you access a ready-made software application over the internet using a browser or app.  The software provider handles everything from hosting, security, updates, and support. You usually pay a subscription fee based on the number of users or features you need. 
    • Used By: End user
    • Examples: Gmail, Dropbox
    • Note: Not every simple website can be considered a SaaS application; while all SaaS applications are technically websites, a website needs to fulfill specific criteria to be classified as SaaS, including being cloud-based, accessible through a web browser, and offering a subscription-based service where users pay to access the software functionality, not just static information on a webpage
  • PAAS: 
    • Definition: PaaS offers a platform for developers to build, test, and deploy applications. It abstracts the infrastructure, allowing developers to focus on coding.
    • Used By: Developers
    • Examples: Google App Service
  • IAAS:
    • Definition: Infrastructure-as-a-Service, commonly referred to as simply “IaaS,” is a form of cloud computing that allows users to manage the server requirements on their own, like, scaling the server, selecting the required cpu and memory, etc. Everything related to the server configuration.
    • Examples: AWS EC2, Google Compute Engine (GCE), IBM Cloud, Microsoft Azure, Rackspace, Linode, Cisco Metacloud, Digital Ocean
    • Used By: Network Architects, IT Administrators, Server Guy
  • Conclusion:
    • Static Website
    • Dynamic Website offering subscriptions, cloud-based services, etc: SAAS (CRM)
    • Every platform (for developer) where cloud provider manages servers, OS, runtime, scaling, and patches: PAAS (AWS RDS because OS, DB, Monitoring, etc is managed by AWS)
    • Every platform, which allows developers to manage the server requirements on their own: IAAS (AWS EC2 because OS, monitoring, availability etc is managed by user)

Design patterns/architectures:

  1. MVC (Also called, Layered Architecture)
  2. Microservice Architecture
  3. Event Driven Design:
    • System reacts to events using EventListeners
  4. Domain-Driven Design:
    • Domain-Driven Design organizes code around business behavior, not technical layers, making complex applications easier to evolve and maintain.
    • Instead of organizing code around technical layers (controllers, services, models), DDD organizes it around business concepts and rules.
    • The layers it has are: Application, Domain Layer (core business logic), Infrastructure Layer (DB, APIs)
  5. CQRS (Command Query Responsibility Segregation) Architecture:
    • Commands: Write (i.e. SendMessageCommand → Write Model)
    • Queries: Read (i.e. GetMessagesQuery → Read Model)
    • Preferred for: Chat, Analytics, Highly read system.

Types of programming:

  • Procedural: Step by step processes of required functions
  • Object-oriented: Class, object, inheritance, code reuse
  • Functional: Programs are built using pure functions
  • Event-driven: Programs based on events

Types of Testing:

  • Unit Test
  • Regression Test: Test to ensure previously developed feature still performs as expected
  • Integration Test: Group Test after merging everything.
  • System Test: Test the entire system.
  • Load Testing
  • Performance Testing
  • Smoke Test: It is a rapid regression test after deploying to production

Types of attacks:

  1. Replay attack: a malicious client generate a request ONCE and replay it MANY times.
  2. DDOS (Distributed Denial of Service) attack: Using a shell script to unnecessarily hit a rival’s application so that it goes down. Rate Limiting is the solution.
  3. Sql attack:
  4. XSS (Cross Site Scription):
    • http request xss
    • database xss
    • frontend xss
    • Solution: Set Content-Type in the http response
  5. CSRF (Cross Site Request Forgery)
    • Example: Change Password Solution: Set CSRF Token

Macro Virus:

A macro virus is a computer virus written in the same macro language used to create software programs such as Microsoft Excel or Word. It centers on software applications and does not depend on the operating system (OS). As a result, it can infect any computer running any kind of OS, including Windows, macOS and Linux.

A PDF or xls file can also contain macro.

Variable Naming Conventions:

  • Snack Case : first_name, FIRST_NAME
  • Camel Case : firstName
  • Pascal Case : FirstName
  • Kebab Case : this-is-kebab-case

Tools:

  • NewRelic: Error Log and Tracking
  • Sentry: Error Log and Tracking
  • Observe: Error Log and Tracking
  • SonarQube
  • Rancher: To check deployed code, access ssh, check log, run command, etc.
  • Blackfire